在C#中,List<T> 是一个非常常用的泛型集合类,属于 System.Collections.Generic 命名空间。List<T> 提供了一种灵活的方式来存储和管理一组元素,这些元素可以是任何类型的对象。下面,我们将详细解析 List<T> 的特性、使用方法、以及一些高级应用。

List<T> 是 C# 中最常用的泛型集合类,位于 System.Collections.Generic 命名空间。它代表一个强类型、可动态调整大小的对象列表,提供了丰富的操作方法,是数组(Array)的现代化替代品。
T 确保集合中只能存储指定类型的元素。list[0]。// 创建空列表List<string> names = new List<string>();// 创建并初始化List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };// 指定初始容量(优化性能)List<double> values = new List<double>(100);List<string> fruits = new List<string>();fruits.Add("Apple"); // 添加单个元素fruits.AddRange(new string[] { "Banana", "Orange" }); // 添加多个元素fruits.Insert(1, "Mango"); // 在指定位置插入List<int> scores = new List<int> { 85, 92, 78 };int firstScore = scores[0]; // 85scores[1] = 95; // 修改第二个元素// 遍历列表foreach (int score in scores){ Console.WriteLine(score);}// 使用 ForEach 方法scores.ForEach(s => Console.WriteLine($"Score: {s}"));List<string> colors = new List<string> { "Red", "Green", "Blue", "Red" };colors.Remove("Red"); // 删除第一个匹配项colors.RemoveAt(0); // 删除指定位置的元素colors.RemoveAll(c => c.StartsWith("B")); // 删除所有满足条件的元素colors.Clear(); // 清空列表| 方法/属性 | 说明 | 示例 |
|---|---|---|
Count | 获取元素数量 | int count = list.Count; |
Add(T item) | 添加元素到末尾 | list.Add("item"); |
AddRange(IEnumerable<T>) | 添加多个元素 | list.AddRange(array); |
Insert(int index, T item) | 在指定位置插入 | list.Insert(0, "first"); |
Remove(T item) | 删除第一个匹配项 | list.Remove("target"); |
RemoveAt(int index) | 删除指定位置元素 | list.RemoveAt(0); |
Contains(T item) | 检查是否包含元素 | bool has = list.Contains("x"); |
IndexOf(T item) | 查找元素索引 | int idx = list.IndexOf("x"); |
Sort() | 排序(默认升序) | list.Sort(); |
Reverse() | 反转元素顺序 | list.Reverse(); |
ToArray() | 转换为数组 | T[] arr = list.ToArray(); |
LinkedList<T>。Capacity 属性:一次性添加大量元素前,可设置合适的容量。AddRange 而非循环 Add。AsReadOnly() 返回只读视图。| 特性 | List<T> | Array |
|---|---|---|
| 大小 | 动态调整 | 固定长度 |
| 性能 | 插入/删除可能需移动元素 | 随机访问最快 |
| 内存 | 有额外开销(容量管理) | 最紧凑 |
| 功能 | 丰富的内置方法 | 基本操作 |
| 适用场景 | 元素数量变化频繁 | 大小固定、性能要求高 |
// 从数据库读取用户列表List<User> users = dbContext.Users.ToList();// 使用 LINQ 筛选List<User> activeUsers = users .Where(u => u.IsActive) .OrderBy(u => u.Name) .ToList();
public class CacheManager<T>{ private List<T> _cache = new List<T>(); public void AddItem(T item) => _cache.Add(item); public T GetItem(Predicate<T> match) => _cache.Find(match);}List<T> 是 C# 开发中不可或缺的集合类型,它结合了数组的索引访问优势和动态集合的灵活性。掌握其基本操作、性能特性和适用场景,能显著提升代码质量和开发效率。在实际项目中,应根据具体需求选择合适的集合类型,List<T> 通常是处理可变序列时的首选。