黑马程序员—最常用的一个集合list

来源:互联网 发布:php基础代码 编辑:程序博客网 时间:2024/05/22 12:56

-------------------- ASP.Net+Android+IO开发S.Net培训、期待与您交流! ---------------------- 

所属命名空间:System.Collections.Generic
List<T> 类是ArrayList 类的泛型等效类。该类使用大小可按需动态增加的数组实现IList<T> 泛型接口。
List<int> list =new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
集合的长度不定,可以按照需要往里边进行添加,可以看做是一个动态的数组。
LIst<Dog> list=new Lsit<>();
list.Add(new Dog()) ;
LIst集合中叶可以添加对象;
数据量比较小的情况用List比较好,当能确定目标数组的长度时,还是使用固定长度的数组更加。
添加元素:
1、 List. Add(T item) 添加一个元素
E.g.: mList.Add("John");
2、 List. AddRange(IEnumerable<T> collection) 添加一组元素
E.g.:
string[] temArr = { "Ha","Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu" };
mList.AddRange(temArr);
3、Insert(int index, T item); 在index位置添加一个元素
E.g.: mList.Insert(1, "Hei");
遍历List中元素:
foreach (T element in mList) T的类型与mList声明时一样
{
Console.WriteLine(element);
}
E.g.:
foreach (string s in mList)
{
Console.WriteLine(s);
}
删除元素:
1、 List. Remove(T item) 删除一个值
 mList.Remove("Hunter");
2、 List. RemoveAt(int index); 删除下标为index的元素
 mList.RemoveAt(0);
3、 List. RemoveRange(int index, int count);
从下标index开始,删除count个元素
mList.RemoveRange(3, 2);
判断某个元素是否在该List中:
List. Contains(T item) 返回true或false,很实用
if (mList.Contains("Hunter"))
{
Console.WriteLine("There is Hunter in the list");
}
else
{
mList.Add("Hunter");
Console.WriteLine("Add Hunter successfully.");
}

给List里面元素排序:
List. Sort () 默认是元素第一个字母按升序
 mList.Sort();
给List里面元素顺序反转:
List. Reverse () 可以与List. Sort ()配合使用,达到想要的效果
 mList.Sort();
List清空:List. Clear ()
mList.Clear();
获得List中元素数目:
int count = mList.Count();
Console.WriteLine("The num of elements in the list: " +count);