📜  C#中的集合(1)

📅  最后修改于: 2023-12-03 15:14:32.478000             🧑  作者: Mango

C#中的集合

C#具有许多预定义的集合和数据结构,开发人员可以使用它们来存储和操作数据。 集合在C#中有两种类型:通用集合和非通用集合。

通用集合

通用集合是一组类型,这些类型是在System.Collections.Generic命名空间中定义的。 这些集合的类型参数允许集合中存储各种类型的对象,并允许类型安全的代码。

List

List是一个数组的变体,它允许快速插入和删除元素。 它受益于数组的连续内存分配,并可以通过调整大小来优化性能。

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.ForEach(n => Console.WriteLine(n));
// Output: 1 2 3
Dictionary

Dictionary<TKey, TValue>是一种键值对的存储结构,其中每个键只能对应一个值。 它提供了快速查找和检索的能力。

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "One");
dict.Add(2, "Two");
dict.Add(3, "Three");
Console.WriteLine(dict[2]);
// Output: Two
HashSet

HashSet是一种存储唯一元素的集合类型,这些元素没有特定的顺序。 它基于哈希表实现,并提供了快速查找和插入元素的能力。

HashSet<int> set = new HashSet<int>();
set.Add(1);
set.Add(2);
set.Add(3);
Console.WriteLine(set.Contains(2));
// Output: True
Queue

Queue是一种先进先出(FIFO)的数据结构,其中元素的添加和删除是从不同的端点进行的。 它提供了快速的插入和删除元素的能力。

Queue<string> queue = new Queue<string>();
queue.Enqueue("James");
queue.Enqueue("John");
queue.Enqueue("Jane");
while(queue.Count > 0)
{
    Console.WriteLine(queue.Dequeue());
}
// Output: James John Jane
Stack

Stack是一种后进先出(LIFO)的数据结构,其中元素的添加和删除是从同一端点(顶部)进行的。 它提供了快速删除和添加元素的能力。

Stack<string> stack = new Stack<string>();
stack.Push("James");
stack.Push("John");
stack.Push("Jane");
while(stack.Count > 0)
{
    Console.WriteLine(stack.Pop());
}
// Output: Jane John James
非通用集合

非通用集合是一类集合类型,它们是集合类的早期版本,现已被通用集合代替。 非通用集合定义在System.Collections和System.Collections.Specialized命名空间中。

ArrayList

ArrayList是一种动态数组,其中每个元素存储为对象。 它提供了一个灵活的、可调整大小的数据结构。

ArrayList list = new ArrayList();
list.Add(1);
list.Add("two");
list.Add(DateTime.Now);
foreach(var item in list)
{
    Console.WriteLine(item.ToString());
}
// Output: 1 two 11/13/2020 11:08:21 AM
Hashtable

Hashtable是一种存储键值对的散列表数据结构,其中键和值都是对象。 它提供了快速的查找和检索能力。

Hashtable table = new Hashtable();
table.Add("John", "Doe");
table.Add("Jane", "Doe");
table.Add("James", "Smith");
foreach(DictionaryEntry entry in table)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}
// Output: John: Doe Jane: Doe James: Smith
NameValueCollection

NameValueCollection是一种存储键值对的数据结构,其中每个键可以对应多个值。 它类似于Dictionary<string, List>,但提供了更简单的访问和修改方法。

NameValueCollection collection = new NameValueCollection();
collection.Add("name", "James");
collection.Add("name", "John");
collection.Add("name", "Jane");
foreach(string value in collection.GetValues("name"))
{
    Console.WriteLine(value);
}
// Output: James John Jane
结论

C#中的集合提供了许多快速、类型安全和灵活的集合和数据结构。 开发人员可以根据具体要求选择适当的集合类型,并使用它们来存储和操作数据。 对于新的代码,建议使用通用集合,以获得更好的性能和类型安全。 对于旧代码,可以考虑升级到通用集合。