5.1 常用集合类(List, Dictionary等)
概述
集合类是C#中用于存储和管理一组相关对象的核心工具,它们提供了高效的数据操作能力。本节将重点介绍System.Collections.Generic命名空间下的常用集合类,包括List<T>、Dictionary<TKey, TValue>等,以及它们的典型应用场景。
1. List<T>:动态数组
基本特性
- 动态大小:无需预先指定容量,自动扩展。
- 泛型支持:类型安全,避免装箱/拆箱开销。
- 索引访问:支持类似数组的
list[0]访问方式。
常用操作
// 初始化
List<string> fruits = new List<string> { "Apple", "Banana" };
// 添加元素
fruits.Add("Orange");
fruits.Insert(1, "Mango"); // 在索引1插入
// 删除元素
fruits.Remove("Apple"); // 按值删除
fruits.RemoveAt(0); // 按索引删除
// 查询
bool hasBanana = fruits.Contains("Banana");
int index = fruits.IndexOf("Mango");
性能注意
- 添加操作:平均O(1),扩容时O(n)。
- 查找元素:
Contains和IndexOf为O(n)。
2. Dictionary<TKey, TValue>:键值对集合
基本特性
- 哈希表实现:基于键的快速查找(接近O(1))。
- 唯一键约束:每个键必须唯一,重复添加会抛出异常。
常用操作
// 初始化
Dictionary<int, string> employees = new Dictionary<int, string>
{
{ 101, "Alice" },
{ 102, "Bob" }
};
// 添加/更新
employees.Add(103, "Charlie");
employees[102] = "Bob Smith"; // 更新值
// 删除
employees.Remove(101);
// 查询
if (employees.TryGetValue(102, out string name))
{
Console.WriteLine(name); // 输出: Bob Smith
}
性能优化
- 自定义键类型:重写
GetHashCode()和Equals()方法以确保正确哈希。 - 初始容量:预估元素数量设置初始容量减少扩容次数。
3. 其他常用集合类
Queue<T>:先进先出(FIFO)
Queue<string> tasks = new Queue<string>();
tasks.Enqueue("Task1");
tasks.Enqueue("Task2");
string nextTask = tasks.Dequeue(); // 返回"Task1"
Stack<T>:后进先出(LIFO)
Stack<string> history = new Stack<string>();
history.Push("Page1");
history.Push("Page2");
string lastPage = history.Pop(); // 返回"Page2"
HashSet<T>:唯一元素集合
- 高性能集合运算(并集、交集等)。
HashSet<int> numbers = new HashSet<int> { 1, 2, 3 };
numbers.Add(2); // 无效,已存在
4. 集合选择指南
| 场景 | 推荐集合类型 |
|---|---|
| 需要频繁按索引访问 | List<T> |
| 快速键值查找 | Dictionary<T> |
| 去重需求 | HashSet<T> |
| 顺序处理任务 | Queue<T> |
| 撤销操作实现 | Stack<T> |
5. 线程安全替代方案
- 并发集合:使用
System.Collections.Concurrent命名空间下的类:ConcurrentBag<T>:无序集合ConcurrentDictionary<T>:线程安全字典BlockingCollection<T>:生产者-消费者模式
总结
掌握常用集合类的特性和适用场景是高效C#开发的关键。建议通过实际项目练习,结合性能分析工具(如Visual Studio Profiler)优化集合的使用。在后续章节中,我们将进一步探讨泛型(5.2节)和LINQ(5.3节)如何与这些集合协同工作。
此内容包含代码示例、性能说明和实用表格,适合读者快速理解并应用集合类。如需扩展特定部分(如线程安全集合的深度示例),可在后续版本中添加。