本章节针对C# 集合(Collections)做全面、详细的知识结构整理,适合系统学习或开发参考。结合 官方文档、实际开发经验 和 高级技巧,涵盖从基础到高级的各类集合类型、差异、应用场景、线程安全、性能比较等内容。
1️⃣ 集合分类概览
| 分类 | 命名空间 | 是否泛型 | 是否线程安全 | 示例 |
|---|---|---|---|---|
| 非泛型集合 | System.Collections | ❌ | ❌ | ArrayList, Hashtable |
| 泛型集合 | System.Collections.Generic | ✅ | ❌ | List<T>, Dictionary<TKey,TValue> |
| 并发集合 | System.Collections.Concurrent | ✅ | ✅ | ConcurrentDictionary, BlockingCollection |
| 特殊集合 | System.Collections.ObjectModel, System.Collections.Specialized | ✅/❌ | 部分支持 | ObservableCollection<T>, NameValueCollection |
🔗 官方文档汇总:https://learn.microsoft.com/en-us/dotnet/standard/collections/
2️⃣ 非泛型集合(System.Collections)
适用于 .NET 早期版本,为了兼容旧代码保留,但不推荐新项目使用。
| 类名 | 功能 | 缺点 |
|---|---|---|
ArrayList | 动态数组 | 装箱拆箱,性能低 |
Hashtable | 基于键值对的哈希表 | 键和值都是 object,需类型转换 |
Queue | FIFO 队列 | 非泛型 |
Stack | LIFO 堆栈 | 非泛型 |
SortedList | 有序字典 | 非泛型,效率略低 |
📌 示例:
ArrayList arr = new ArrayList();
arr.Add(100);
arr.Add("text");
3️⃣ 泛型集合(System.Collections.Generic)
主流开发中最常用集合类。优势包括类型安全、高性能、LINQ 支持、清晰的结构设计。
常用泛型集合类及应用场景
| 类 | 描述 | 特点 |
|---|---|---|
List<T> | 可变长度数组 | 快速索引 |
LinkedList<T> | 双向链表 | 适合频繁插入删除 |
Dictionary<TKey,TValue> | 哈希表结构 | 快速键值查找 |
SortedDictionary<TKey,TValue> | 自动排序的字典 | 按键排序 |
SortedList<TKey,TValue> | 有序键值对集合 | 较快检索但插入慢 |
Queue<T> | 先进先出 | 适合任务处理 |
Stack<T> | 后进先出 | 适合撤销操作 |
HashSet<T> | 元素唯一 | 数学集合运算 |
SortedSet<T> | 自动排序且无重复 | 高级集合处理 |
📌 示例:
var nums = new List<int> {1, 2, 3, 4};
var dict = new Dictionary<string, int> {
{"a", 1}, {"b", 2}
};
🔗 List<T> 官方文档:https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1
4️⃣ 并发集合(System.Collections.Concurrent)
用于多线程/异步场景,内部采用锁或无锁机制实现。
| 类 | 描述 | 特点 |
|---|---|---|
ConcurrentDictionary<TKey,TValue> | 线程安全哈希表 | 高并发写入 |
BlockingCollection<T> | 提供阻塞添加/移除 | 可限制容量,适合生产者消费者 |
ConcurrentQueue<T> | 线程安全 FIFO | 非阻塞 |
ConcurrentStack<T> | 线程安全 LIFO | 非阻塞 |
ConcurrentBag<T> | 无序线程安全集合 | 高效批量处理 |
📌 示例:
var dict = new ConcurrentDictionary<string, int>();
dict.TryAdd("k1", 1);
dict["k2"] = 2;
🔗 官方文档:https://learn.microsoft.com/en-us/dotnet/standard/collections/thread-safe/
5️⃣ 特殊集合
5.1 ObservableCollection(常用于 MVVM)
实现 INotifyCollectionChanged,适合数据绑定。
🔗 https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1
ObservableCollection<string> items = new ObservableCollection<string>();
items.CollectionChanged += (s, e) => Console.WriteLine("Changed!");
items.Add("Hello");
5.2 NameValueCollection & StringCollection
适用于 WebForm、传统配置传递。
NameValueCollection queryParams = new NameValueCollection();
queryParams.Add("key", "value");
🔗 https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.namevaluecollection
6️⃣ 集合操作方法
Add,Remove,Clear,ContainsInsert,IndexOf(适用于 List)TryGetValue(适用于 Dictionary)- 集合遍历(
foreach) - 集合拷贝(
ToArray(),Clone())
if (!dict.ContainsKey("test")) {
dict.Add("test", 123);
}
7️⃣ LINQ 与集合
LINQ 是 .NET 提供的强大查询机制,常用于集合查询、筛选、排序、分组等。
📌 示例:
var even = nums.Where(n => n % 2 == 0).ToList();
var grouped = people.GroupBy(p => p.Age);
🔗 LINQ 教程:https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
8️⃣ 性能与选择建议
| 需求 | 推荐集合 | 原因 |
|---|---|---|
| 快速访问索引 | List<T> | O(1) 访问时间 |
| 频繁插入删除 | LinkedList<T> | 链表操作快 |
| 无重复集合 | HashSet<T> | 集合数学运算高效 |
| 排序集合 | SortedSet<T>, SortedList | 自动排序 |
| 键值对查询 | Dictionary | 哈希查询快 |
| 多线程共享数据 | ConcurrentDictionary | 无锁高性能 |
9️⃣ 集合扩展方法与自定义
C# 支持为集合编写扩展方法,例如:
public static class CollectionExtensions
{
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> items)
{
foreach (var item in items)
collection.Add(item);
}
}
使用:
list.AddRange(new[] { 4, 5, 6 });
🔟 自定义集合类(继承与封装)
你可以继承现有集合类或实现 ICollection<T>, IDictionary<TKey,TValue> 以定制逻辑(如只读、带日志等)。
public class ReadOnlyList<T> : List<T>
{
public new void Add(T item)
{
throw new InvalidOperationException("只读集合无法添加元素");
}
}
📌 实战建议
- 永远首选泛型集合(
List<T>等) - 多线程场景选用
System.Collections.Concurrent - UI 绑定推荐
ObservableCollection<T> - 性能敏感区域避免频繁使用
ToList()、AddRange()等创建副本操作 - 合理选择集合可提升程序效率与可维护性
更多详细内容请关注其他相关文章!