C#高级编程四十八天

时间:2022-04-19 04:59:55

C#deList怎么样?List<T>类是ArrayList类的泛型等效类,该类使用大小可按需动态增长的数组实现List<T>泛型接口.

泛型的优点:它为使用C#语言编写面向对象程序添加了极大的效力和灵活性,不会强行对值类型进行装箱和拆箱,或对引用类型进行向下强制类型转化,所以性能得到提高.

性能注意事项:再决定使用List<T>还是使用ArrayList(两者具有类似的功能),记住IList<T>类在大多数情况下运行得更好而且是类型安全的.假设对IList<T>类的类型T使用引用类型,则两个类的行为是全然同样的,可是假设对类型T使用值类型,则须要考虑实现和装箱问题.

C#List的基础经常用法:

一.声明:

1.  List<T> list=new List<T>():

T为列表中元素类型,如今以string类型作为样例:

List<string> list=new List<string>():

2.List<T> list = new List<T>(IEnumerable<T> collection);

以一个集合作为參数创建List:

string[] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu" };

List<string> testList = new List<string>(temArr);

二.加入元素:

1. List.Add( Titem)加入一个元素

比如:testList.Add(“hahaha”);

2. List.AddRange(IEnumerable <T> collection)  加入一组元素

:            string[] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu" };

List<string> testList = new List<string>();

testList.AddRange(temArr);

3.  Insert(int index ,T item) ; index位置加入一个元素

:testList.Insert(1,”hello”);

三.遍历List中的元素:

案例:

string[] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu" };

List<string> testList = new List<string>();

testList.AddRange(temArr);

foreach (var item in testList)

{

Console.WriteLine(item);

}

四.删除元素:

1.List.Remove(T item)删除一个值

:mList.Remove(“hahaha”);

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) 返回truefalse,非常有用

:            string[] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu" };

List<string> testList = new List<string>();

testList.AddRange(temArr);

if (testList.Contains("Hunter"))

{

Console.WriteLine("There is Hunter in the list");

}

else

{

testList.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中元素数目:

  List. Count ()返回int

  例:

  in tcount = mList.Count();

  Console.WriteLine("The num of elements in the list: "+count);

综合案例:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace 集合

{

class Program

{

static void Main(string[] args)

{

//比較List<T>(泛型的)ArrayList(非泛型的)

People p1 = new People("zhangsan", 21);

People p2 = new People("lisi", 11);

People p3 = new People("wangwu", 41);

//People对象加到集合中

List<People> list = new List<People>(4);

list.Add(p1);

list.Add(p2);

list.Add(p3);