一、集合
是一组对象的容器,提供了高效的存储、检索和操作数据的方式。
C# 集合分为泛型集合(推荐使用)和非泛型集合,主要位于System.Collections
和System.Collections.Generic
命名空间中。
二、集合有哪些?
1)数组
之前学过了哈,就不详细说明了,记住有二维,多维,交错等等
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
2)List<T>(动态数组)
特点:动态大小、可随机访问、支持增删改查。
适用场景:需要频繁随机访问元素的场景。
eg::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
using System.Collections.Generic;
List<int> numbers = new List<int> { 1, 2, 3 };
numbers.Add(4); // 添加元素
numbers.Insert(0, 0); // 插入元素
numbers.Remove(2); // 移除值为2的元素
int first = numbers[0]; // 随机访问
3) Queue<T>(队列)
特点:先进先出(FIFO),支持入队(Enqueue)和出队(Dequeue)。
适用场景:任务调度、消息处理。
eg::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Queue<string> tasks = new Queue<string>();
tasks.Enqueue("Task1"); // 入队
tasks.Enqueue("Task2");
string nextTask = tasks.Dequeue(); // 出队,返回"Task1"
4) Stack<T>(栈)
特点:后进先出(LIFO),支持入栈(Push)和出栈(Pop)。
适用场景:表达式计算、撤销操作。
eg::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Stack<int> stack = new Stack<int>();
stack.Push(1); // 入栈
stack.Push(2);
int top = stack.Pop(); // 出栈,返回2
5)字典 (Dictionary)
Dictionary<TKey, TValue>(键值对)
特点:基于哈希表,键唯一,查找速度快(O (1))。
适用场景:需要通过键快速查找值的场景。
eg::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Dictionary<string, int> ages = new Dictionary<string, int> {
{ "Alice", 25 },
{ "Bob", 30 }
};
ages["Charlie"] = 35; // 添加或修改键值对
bool hasAlice = ages.ContainsKey("Alice"); // 检查键是否存在
int bobAge = ages["Bob"]; // 通过键获取值
6) HashSet<T>(无序唯一集合)
特点:元素唯一,不保证顺序,插入 / 删除 / 查找效率高。
适用场景:去重、成员检测。
eg::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
HashSet<int> uniqueNumbers = new HashSet<int> { 1, 2, 2, 3 }; // 实际只包含1,2,3
uniqueNumbers.Add(4); // 添加成功
uniqueNumbers.Add(2); // 添加失败(已存在)
bool contains3 = uniqueNumbers.Contains(3); // 检查是否包含
三、集合选择指南
需要唯一元素:
HashSet<T>(无序)或SortedSet<T>(有序)。
需要键值对:
Dictionary<TKey, TValue>(快速查找)或SortedDictionary<TKey, TValue>(有序)。
需要特定顺序:
List<T>(按插入顺序)或SortedList<TKey, TValue>(按键排序)。
需要先进先出 / 后进先出:
Queue<T>(队列)或Stack<T>(栈)。
四、集合性能对比
操作 | List<T> | Dictionary<T> | HashSet<T> | SortedSet<T> |
---|---|---|---|---|
随机访问 | O(1) | O(1) | 不支持 | 不支持 |
插入 / 删除末尾 | O(1) | O(1) | O(1) | O(log n) |
插入 / 删除中间 | O(n) | O(1) | O(1) | O(log n) |
查找 | O(n) | O(1) | O(1) | O(log n) |
排序 | O(n log n) | 不支持 | 不支持 | 自动维护 |