泛型list的底层是动态数组,其容量可自动或手动调整。

1
2
3
4
5
6
7
8
9
10
class Program {
static void Main(string[] args) {
List<int> IntList = new List<int>();
IntList.Add(1);
IntList.Add(2);
IntList.Add(3);
Console.WriteLine(IntList.Count);//集合元素的数量
Console.WriteLine(IntList.Capacity);//底层数组长度
}
}

可以向()中传入一个整数来限制list的底层数组大小。

List常用API

list.Add(int value) 添加元素

list.AddRange(IEnumerable <int> list) 添加一组元素

list.Insert(int index,int value) 插入元素

list.InsertRange(int index,IEnumerable <int>list) 插入一组元素

list.Clear() 清空(底层数组长度不变)

list.Remove(int index) 移除

list.RemoveRange(int index,int length) 移除length个元素

list.RemoveAll(e=>e==400) 接受一个返回值为bool的委托,移除满足条件的成员

list.GetRange(int index,int length) 返回一个List <int>类型的对象,包含被截取的成员

list.GetEnumerator() 返回List <int>类型对象的Enumerator迭代器,迭代器会在之后的篇章中介绍。

list.ForEach(e=>e*10) 遍历

list.Contain(100) 返回bool,检测一个值是否存在于list中

list.Exists(e=>e>500)) 返回bool,用来检测list中是否有满足条件的元素

list.TrueForAll(e=>e<=40) 返回bool,检测所有元素是否都满足要求

list.IndexOf(300) 返回第一个值为300的成员的索引,底层调用==,没有则返回-1

list.IndexOf(value,index) 从index位置开始,往后找value所在的索引,index最大为list.Count,再大就报错了

list.IndexOf(value,startIndex,much) 从stratIndex位置开始,到其往后much个元素位置,查找是否有value,返回value的索引

list.Find(e=>e%3==0) 返回第一个满足要求的值

list.FindLast(e=>e%4==0) 返回最后一个满足要求的值

list.FindAll(e=>e%3==0) 返回一个由满足要求的值组成的新集合

list.FindIndex(e=>e%2==0)

list.FindIndex(index,e=>e%2==0)

list.FindIndex(index,much,e=>e%2==0)

list.FindLastIndex(e=>e%2==0)

list.FindLastIndex(index,e=>e%2==0)

list.FindLastIndex(index,much,e=>e%2==0)

list.BinarySearch(value) 在排好序的list中用二分查找value所在的位置

list.Contain()

其底层原理是==,如果是引用类型则用Equals方法,自定义类型没有Equals方法需要覆写object的Equals方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Program {
static void Main(string[] args) {
List<Book> list = new List<Book>();
Book book1 = new Book();
Book book2 = new Book();
book1.id = 1;
book2.id = 2;
list.Add(book1);
list.Add(book2);
Console.WriteLine(list.Contains(book1));
}
}
class Book {
public int id;
public override bool Equals(object? obj) {
if(obj ==null) return false;
Book other = obj as Book;
if(other == null) return false;
return this.id == other.id;
}
}

list.Sort()

其底层用CompareTo方法,引用类型没有CompareTo方法所以要自己写,要求该引用类型实现IComparable<>接口/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Program {
static void Main(string[] args) {
Book book1 = new Book();
Book book2 = new Book();
Book book3 = new Book();
book1.ID = 9;
book2.ID=4;
book3.ID=15;
List<Book> list = new List<Book>{ book1,book2,book3};
list.Sort();
foreach (Book book in list) {
Console.WriteLine(book.ID);
}
}
}
class Book:IComparable<Book> {
public int ID { get; set; }
public int CompareTo(Book? obj) {
if (obj == null) return 1;
return this.ID - obj.ID;
}
}