C#中的Collection集合

生成模型:DeepSeek-R1,生成时间:2025 03-18 21:14

在 C# 中,集合(Collection) 是一组用于存储和管理多个对象的容器,它们比数组更灵活,支持动态调整大小、快速查找和多种操作。集合主要分为以下两类:

  1. 非泛型集合(位于 System.Collections 命名空间,如 ArrayListHashtable

  2. 泛型集合(位于 System.Collections.Generic 命名空间,如 List<T>Dictionary<TKey, TValue>

推荐优先使用泛型集合,因为它们提供更好的类型安全和性能。

常见泛型集合类型及示例

1. List<T>:动态数组

using System.Collections.Generic;
// 创建列表并添加元素
List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");
// 通过索引访问
Console.WriteLine(fruits[0]); // 输出: Apple
// 遍历列表
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
// 删除元素
fruits.Remove("Banana");

2. Dictionary<TKey, TValue>:键值对集合

Dictionary<int, string> employees = new Dictionary<int, string>();
employees.Add(1, "Alice");
employees.Add(2, "Bob");
employees.Add(3, "Charlie");
// 通过键获取值
Console.WriteLine(employees[2]); // 输出: Bob
// 遍历键值对
foreach (KeyValuePair<int, string> entry in employees)
{
    Console.WriteLine($"ID: {entry.Key}, Name: {entry.Value}");
}
// 检查键是否存在
if (employees.ContainsKey(3))
{
    Console.WriteLine("员工3存在");
}

3. HashSet<T>:唯一元素集合

HashSet<int> numbers = new HashSet<int> { 1, 2, 3, 3, 4 };
// 自动去重,实际存储 {1, 2, 3, 4}
// 检查元素是否存在
if (numbers.Contains(2))
{
    Console.WriteLine("2在集合中");
}
// 添加元素
numbers.Add(5);

4. Queue<T>:先进先出(FIFO)队列

Queue<string> queue = new Queue<string>();
queue.Enqueue("Task1"); // 入队
queue.Enqueue("Task2");
// 出队(按顺序处理)
string nextTask = queue.Dequeue(); // 返回 "Task1"
Console.WriteLine(nextTask);

5. Stack<T>:后进先出(LIFO)栈

Stack<string> stack = new Stack<string>();
stack.Push("Book1"); // 入栈
stack.Push("Book2");
// 出栈(最后放入的先取出)
string topBook = stack.Pop(); // 返回 "Book2"
Console.WriteLine(topBook);

集合的通用操作

  • 添加元素Add()(多数集合)、Enqueue()(队列)、Push()(栈)

  • 删除元素Remove()Dequeue()(队列)、Pop()(栈)

  • 查找元素Contains()ContainsKey()(字典)

  • 遍历:使用 foreach 循环

如何选择合适的集合?

  • 需要快速通过键查找值 → Dictionary<TKey, TValue>

  • 需要动态调整大小的数组 → List<T>

  • 需要唯一元素 → HashSet<T>

  • 需要先进先出处理 → Queue<T>

  • 需要后进先出处理 → Stack<T>

非泛型集合示例(了解即可)

using System.Collections;
ArrayList list = new ArrayList();
list.Add(100); // 可以添加任意类型
list.Add("Hello");
// 但取出时需要类型转换
int num = (int)list[0]; // 不安全,可能出错

注意:非泛型集合容易导致类型错误和性能问题,优先使用泛型集合!