天天看點

C#入門7.10——ArrayList類中元素的删除

ArrayList類中元素的删除有以下四種方法:

1.ArrayList變量名.Remove(要删除的值);

2.ArrayList變量名.RemoveAt(索引值);

3.ArrayList變量名.RemoveRange(開始索引值,要删除的個數);

4.ArrayList變量名.Clear(); //清空。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;//引用命名空間
using System.Threading.Tasks;
using System.Collections;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            //元素删除有四種方法
            ArrayList myArrayList = new ArrayList(3);
            myArrayList.Add(1);
            myArrayList.Add("成功");
            myArrayList.Add(25.63);
            string[] mystringArray = { "張三","李四","王武","趙柳" };
            myArrayList.AddRange(mystringArray);
            Console.WriteLine("删除之前的内容:");
            foreach (object outElement in myArrayList) Console.Write(outElement);
            //Remove(值)
            Console.WriteLine("\n删除之後的内容為:");
            myArrayList.Remove("張三");
            foreach (object outElement in myArrayList) Console.Write(outElement+"\t");

            //RemoveAt(索引值)
            Console.WriteLine("\n删除 李四 之後的内容為:");
            myArrayList.RemoveAt(3);
            foreach (object outElement in myArrayList) Console.Write(outElement+"\t");
            //RemoveRange(起始索引,删除個數);
            Console.WriteLine("\n删除 王武 趙柳 之後的内容為:");
            myArrayList.RemoveRange(3, 2);
            foreach (object outElement in myArrayList) Console.Write(outElement+"\t");

            //Clear()
            Console.WriteLine("\n清除所有元素:");
            myArrayList.Clear();
            foreach (object outElement in myArrayList) Console.Write(outElement+"\t");

            Console.ReadKey();
        }

    }
}