上一篇: C# 事件(Event)
下一篇: C# 泛型(Generic)
C# 集合(Collection)
在本教程中,我们将学习C#集合(Collection)的基本概念及其应用。
- 集合简介
- 列表(List)
- 字典(Dictionary)
- 队列(Queue)
- 栈(Stack)
- 其他集合类型
集合简介
集合(Collection)是一种用于存储和操作数据的容器。C# 提供了许多不同类型的集合类,以满足各种数据结构需求。它们大多数都位于 System.Collections
和
System.Collections.Generic
命名空间中。
列表(List)
列表(List)是一种可调整大小的动态数组,可以在其末尾添加、插入或删除元素。
using System.Collections.Generic; List<int> numbers = new List<int>(); numbers.Add(1); numbers.Add(2); numbers.Add(3); foreach (int number in numbers) { Console.WriteLine(number); // 输出 "1", "2", "3" }
字典(Dictionary)
字典(Dictionary)是一种键值对映射的集合。通过键来存储和检索值。键必须是唯一的。
using System.Collections.Generic; Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 }, { "Charlie", 20 } }; ages["David"] = 35; int ageOfAlice = ages["Alice"]; // 30 bool isExists = ages.ContainsKey("Eve"); // false foreach (KeyValuePair<string, int> entry in ages) { Console.WriteLine($"Name: {entry.Key}, Age: {entry.Value}"); }
队列(Queue)
队列(Queue)是一种先进先出(FIFO)的数据结构。元素被添加到队列尾部,并从头部移除。
using System.Collections.Generic; Queue<string> names = new Queue<string>(); names.Enqueue("Alice"); names.Enqueue("Bob"); names.Enqueue("Charlie"); string firstInLine = names.Dequeue(); // "Alice"
栈(Stack)
栈(Stack)是一种后进先出(LIFO)的数据结构。元素被添加到栈顶,并从栈顶移除。
using System.Collections.Generic; Stack<string> books = new Stack<string>(); books.Push("Book1"); books.Push("Book2"); books.Push("Book3"); string topBook = books.Pop(); // "Book3"
其他集合类型
除了上述几种常用的集合外,C#还提供了其他一些集合类型,例如:
HashSet<T>
:一种无序且唯一元素的集合。LinkedList<T>
:一种双向链表结构,允许在常数时间内在任意位置插入或删除元素。SortedSet<T>
:一种有序且不含重复元素的集合,它基于二叉搜索树实现。SortedList<TKey, TValue>
:一种按键排序的字典。
创建和使用这些集合的方法与前面介绍过的集合类似,具体可参考官方文档和示例。
using System.Collections.Generic; // 示例:创建并使用一个 HashSet HashSet<string> uniqueNames = new HashSet<string>(); uniqueNames.Add("Alice"); uniqueNames.Add("Bob"); uniqueNames.Add("Alice"); // 尝试添加重复项,但不会成功 foreach (string name in uniqueNames) { Console.WriteLine(name); // 输出 "Alice", "Bob" }
总结
本教程简要介绍了C#集合的基本概念及其应用,包括列表、字典、队列、栈等常用集合类型。熟练掌握这些集合类型及其操作有助于在实际编程中更高效地处理数据结构和算法问题。