命名空间:System.Collections.Generic
List<T>类是ArrayList类的泛型等效类。该类使用大小可按需动态增加的数组实现IList<T>泛型接口。
泛型的好处(?)
不会强行对值类型进行装箱和拆箱,或对引用类型进行向下强制类型转换,所以性能得到提高。
添加到 ArrayList 中的任何引用或值类型都将隐式地向上强制转换为 Object。
1:List的基础,常用方法:
声明:
1. List<T> mList = new List<T>();
T为列表中元素类型,现在以string类型作为例子
EG:List<string> mList = new List<string>();
2:
添加元素
1:List.Add(T item)
EG: mList.Add("John");
添加一组数据
3:Insert(int index,T item);在index位置添加一个元素
EG: mList.Insert(1,"Hei");
遍历List中的元素
foreach(T element in mList) ///////T的类型与mList声明时一样
{
Console.WriteLine(element);
}
EG:
foreach(string s in mList)
{
Console.WriteLine(s);
}
删除元素
1:List.Remove(T item) 删除一个值
EG:mList.Remove("Hunter");
2:List.RemoveAt(int index);删除下标为index的元素
EG: mList.RemoveAt(0);
3:List.RemoveRange(int index,int count); 从下标index开始,删除count个元素
EG: mList.RemoveRange(3,2);