一、集合:专门用来数组存储和检索
泛型集合:List(通过索引访问元素)、Dictionary(通过key访问元素)、
非泛型集合:ArrayList(通过索引访问元素)、Hashtable(通过key访问元素)、BitArray(通过整型索引访问)
既有泛型又有非泛型:SortedList(通过索引和key访问元素)、Stack、Queue
1.ArrayList:动态数组。当中间元素被删除时,后面的元素会前移
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CollectionTest
{
internal class Program
{
static void Main(string[] args)
{
ArrayList arrayList = new ArrayList();
//常用方法
arrayList.Add(123);//添加元素
arrayList.Insert(1, "动态数组");//在指定索引处插入元素
arrayList.Remove(123);//移除元素
arrayList.RemoveAt(0);//移除指定索引处的元素
Console.WriteLine(arrayList.Contains("动态数组"));//判断是否包含某元素
Console.WriteLine(arrayList.IndexOf("动态数组"));//获取某元素的索引
arrayList.Reverse();//逆置动态数组中的元素
arrayList.Sort();//对动态数组排序
arrayList.Clear();//清空元素
//arraylist.ToArray(); 将arraylist转为数组
//常用属性
int num=arrayList.Count;//动态数组中实际的元素个数
arrayList[0] = 123;//获取或设置指定索引的元素
}
}
}
更多内容:C# 动态数组(ArrayList) | 菜鸟教程
2.List:链表。当中间元素被删除时,后面的元素会前移
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CollectionTest
{
internal class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
//常用方法
list.Add(123);//添加元素
list.Insert(1, 234);//在指定索引处插入元素
list.Remove(123);//移除元素
list.RemoveAt(0);//移除指定索引处的元素
Console.WriteLine(list.Contains(234));//判断是否包含某元素
Console.WriteLine(list.IndexOf(234));//获取某元素的索引
list.Reverse();//逆置动态数组中的元素
list.Sort();//对动态数组排序
list.Clear();//清空元素