List<T>泛型列表
List<T>是 C# 中最常用的动态数组集合,T代表存储的数据类型(如int/string/ 自定义类),长度可自动扩容,比普通数组更灵活。
在目前的学习中,我认为相比string类、DateTime类和数学类使用更多,更难以理解,所以写一篇总结
一、基础创建与初始化
// 1. 空列表创建 List<int> numList = new List<int>(); List<string> strList = new List<string>(); // 2. 创建时直接初始化 List<int> numList2 = new List<int> { 1, 2, 3, 4 }; List<string> strList2 = new List<string> { "张三", "李四", "王五" };二、增删改查操作
1.添加元素
//添加单个元素 numbers.Add(1); // 添加多个元素 numbers.AddRange(new int[] { 2, 3, 4 }); //在末尾添加数组 numbers.AddRange(数组名)2.删除元素
// 删除指定元素(第一个匹配项) list.Remove(20); // 删除指定索引元素 list.RemoveAt(0); // 按条件批量删除* list.RemoveAll(x => x > 20); // 清空所有元素 list.Clear();3.修改元素
list[0] = 100; // 直接通过索引赋值修改4.查询 / 访问元素
// 按索引访问 int first = list[0]; numbers[1] = 10; // 通过索引修改 // 常用查询方法 int count = list.Count; // 获取元素个数(不是Capacity) bool hasElement = list.Contains(10); // 判断是否包含元素 int index = list.IndexOf(10); // 获取元素索引(不存在返回-1)注:var为自适应类型,让编译器自动推断变量的类型
三、遍历列表
// foreach 循环 (最常用) foreach (int num in numbers) { Console.WriteLine(num); } // for 循环 (需要索引时使用) for (int i = 0; i < numbers.Count; i++) { Console.WriteLine($"索引{i}:{names[i]}"); }四、排序与反转
List<int> list = new List<int> { 3, 1, 4, 2 }; list.Sort(); // 升序排序(默认) list.Reverse(); // 反转元素顺序 // 自定义排序(如降序) list.Sort((a, b) => b.CompareTo(a));五、查找
// 条件查询 var result = list.Find(x => x > 5); // 查找第一个符合条件的元素 var allResult = list.FindAll(x => x > 5); // 查找所有符合条件的元素 var result = list.FindLast(x => x > 5);//查找最后一个符合条件的元素 // 二分查找(仅适用于已排序的列表,效率远高于线性查找) List<int> sortedList = new List<int> { 1, 3, 5, 7, 9 }; int position = sortedList.BinarySearch(5); // 返回索引2 int notFound = sortedList.BinarySearch(6); // 返回负数(表示插入位置)六、自动扩容机制
- 初始容量:默认
Capacity = 0,第一次添加元素时扩容到4 - 扩容策略:每次容量不足时,翻倍扩容(4→8→16→32...)
- 扩容过程:创建一个新的更大的数组,将旧数组的所有元素复制到新数组,然后丢弃旧数组
- 性能影响:频繁扩容会导致大量的数组复制操作,降低性能
总结
核心特性:动态长度、泛型安全、索引访问、增删改查便捷;
高频方法:
Add/Remove/Sort/Find/Count/ToArray;适用场景:需要频繁增删元素、长度不固定的集合数据、主要在列表末尾进行增删操作。
