C# 泛型List<T>学习总结

来源:互联网 发布:淘宝售后换货流程 编辑:程序博客网 时间:2024/06/05 03:04

泛型List<T>的好处:在使用的效率上比Array类型效率上高的可不是一截,List,<T>避免反复装箱,拆箱的麻烦,同时其大小可以随用户的要求动态变化,避免类型的强制转换!

1.初始化:

List<T> listName=new List<T> ();

其中T为要创建List的数据类型;

eg.

list<int> myList=new list<int>();

2.相关方法:(用例接上myList)

(1)增加元素:List<T>.Add(T t);

eg.

a=10;

myList.Add(a);

(2)插入元素:

Insert(int index, T item),其中index为插入位置,item为插入数据

eg.myList.Insert(1,3);

(3)删除元素:

removeAt(int index)删除下标为Index的元素

remove(T item);删除值为Item的元素

removeRange(int index ,int count) 删除从下标为index 开始个数为count的元素

注意:删除元素后,后面的元素会自动跟上,同时如果删除个数不足的话会抛出异常;

(4)判断是否存在元素:

Contains(T item);判断是否存在item元素,有则返回true,否则返回false;

(5)升序\降序:

List.sort()将List中的元素按升序排列

List.reverse()将原来的顺序逆序排列

(6)清空list:

myList.Clear();

(7)获得List的元素个数:

myList.count();返回int个数;

(8)List<T>与数组之间的转换:

1.将List<T>转化为Array

String str = myList.ToArray();

2.将Array转化为List

List<int > myList=new List<int>(str);

0 0
原创粉丝点击