集合和数据结构Collections and Data Structures

类似的数据在作为集合而存储和操作时通常可以得到更高效地处理。Similar data can often be handled more efficiently when stored and manipulated as a collection. 可使用 System.Array 类或 System.CollectionsSystem.Collections.GenericSystem.Collections.Concurrent 和 System.Collections.Immutable 命令空间中的类来添加、移除和修改集合中的单个元素或一系列元素。You can use the System.Array class or the classes in the System.Collections, System.Collections.Generic, System.Collections.Concurrent, System.Collections.Immutable namespaces to add, remove, and modify either individual elements or a range of elements in a collection.

有两种主要的集合类型:泛型集合和非泛型集合。There are two main types of collections; generic collections and non-generic collections. 泛型集合被添加在 .NET Framework 2.0 中,并提供编译时类型安全的集合。Generic collections were added in the .NET Framework 2.0 and provide collections that are type-safe at compile time. 因此,泛型集合通常能提供更好的性能。Because of this, generic collections typically offer better performance. 构造泛型集合时,它们接受类型形参;并在向该集合添加项或从该集合删除项时无需在 Object 类型间来回转换。Generic collections accept a type parameter when they are constructed and do not require that you cast to and from the Object type when you add or remove items from the collection. 此外,Windows 应用商店应用支持大多数泛型集合。In addition, most generic collections are supported in Windows Store apps. 非泛型集合将项存储为 Object,需要强制转换,并且大多数不支持 Windows 应用商店应用开发。Non-generic collections store items as Object, require casting, and most are not supported for Windows Store app development. 但是,你可能会看到在较旧的代码中有非泛型集合。However, you may see non-generic collections in older code.

自 .NET Framework 4 起,System.Collections.Concurrent 命名空间中的集合可提供高效的线程安全操作,以便从多个线程访问集合项。Starting with the .NET Framework 4, the collections in the System.Collections.Concurrent namespace provide efficient thread-safe operations for accessing collection items from multiple threads. System.Collections.Immutable 命名空间(NuGet 包)中的不可变集合类本质上就是线程安全的,因为是在原始集合的副本上执行操作,且不能修改原始集合。The immutable collection classes in the System.Collections.Immutable namespace (NuGet package) are inherently thread-safe because operations are performed on a copy of the original collection and the original collection cannot be modified.

常用集合功能Common collection features

所有集合都提供用于在集合中添加、删除或查找项的方法。All collections provide methods for adding, removing or finding items in the collection. 此外,所有直接或间接实现 ICollection 接口或 ICollection<T> 接口的集合均共享这些功能:In addition, all collections that directly or indirectly implement the ICollection interface or the ICollection<T> interface share these features:

此外,许多集合类包含下列功能:In addition, many collection classes contain the following features:

  • 容量和计数属性Capacity and Count properties

    集合的容量是它可包含的元素数。The capacity of a collection is the number of elements it can contain. 集合的计数是它实际所含的元素数。The count of a collection is the number of elements it actually contains. 某些集合隐藏容量、计数或将这两者都隐藏。Some collections hide the capacity or the count or both.

    达到当前容量时,大多数集合会自动扩展容量。Most collections automatically expand in capacity when the current capacity is reached. 重新分配内存并将元素从旧集合复制到新集合。The memory is reallocated, and the elements are copied from the old collection to the new one. 这减少了要求使用集合的代码;但集合的性能可能会受到不利影响。This reduces the code required to use the collection; however, the performance of the collection might be negatively affected. 例如,对 List<T> 来说,如果 CountCapacity 少,那么添加项就是一项 O(1) 操作。For example, for List<T>, If Count is less than Capacity, adding an item is an O(1) operation. 如需增加容量以容纳新元素,则添加项成为 O(n) 操作,其中 n 是 CountIf the capacity needs to be increased to accommodate the new element, adding an item becomes an O(n) operation, where n is Count. 避免因多次重新分配而导致的性能较差的最佳方式是:将初始容量设置为集合的估计大小。The best way to avoid poor performance caused by multiple reallocations is to set the initial capacity to be the estimated size of the collection.

    BitArray 是一种特殊情况;它的容量与其长度相同,而其长度与其计数相同。A BitArray is a special case; its capacity is the same as its length, which is the same as its count.

  • 下限一致A consistent lower bound

    集合的下限是其第一个元素的索引。The lower bound of a collection is the index of its first element. System.Collections 命名空间中的所有索引集合的下限均为零,这表示它们从 0 开始建立索引。All indexed collections in the System.Collections namespaces have a lower bound of zero, meaning they are 0-indexed. Array 默认下限为零,但使用 Array.CreateInstance 创建 Array 类的实例时可定义其他下限 。Array has a lower bound of zero by default, but a different lower bound can be defined when creating an instance of the Array class using Array.CreateInstance.

  • 同步以从多个线程进行访问(仅 System.Collections 类)。Synchronization for access from multiple threads (System.Collections classes only).

    System.Collections 命名空间中的非泛型集合类型通过同步提供一些线程安全性;通常通过 SyncRootIsSynchronized 成员公开。Non-generic collection types in the System.Collections namespace provide some thread safety with synchronization; typically exposed through the SyncRoot and IsSynchronized members. 这些集合不是默认为线程安全的。These collections are not thread-safe by default. 如需对集合进行可扩展、高效的多线程访问,请使用 System.Collections.Concurrent 命名空间中的一个类或考虑使用不可变集合。If you require scalable and efficient multi-threaded access to a collection, use one of the classes in the System.Collections.Concurrent namespace or consider using an immutable collection. 有关详细信息,请参阅线程安全集合For more information, see Thread-Safe Collections.

选择集合Choosing a collection

一般情况下,应使用泛型集合。In general, you should use generic collections. 下表介绍了一些常用的集合方案和可用于这些方案的集合类。The following table describes some common collection scenarios and the collection classes you can use for those scenarios. 如果你是使用泛型集合的新手,此表将帮助你选择最适合你的任务的泛型集合。If you are new to generic collections, this table will help you choose the generic collection that works the best for your task.

我要……I want to… 泛型集合选项Generic collection options 非泛型集合选项Non-generic collection options 线程安全或不可变集合选项Thread-safe or immutable collection options
将项存储为键/值对以通过键进行快速查找Store items as key/value pairs for quick look-up by key Dictionary<TKey,TValue> Hashtable

(根据键的哈希代码组织的键/值对的集合。)(A collection of key/value pairs that are organized based on the hash code of the key.)
ConcurrentDictionary<TKey,TValue>

ReadOnlyDictionary<TKey,TValue>

ImmutableDictionary<TKey,TValue>
按索引访问项Access items by index List<T> Array

ArrayList
ImmutableList<T>

ImmutableArray
使用项先进先出 (FIFO)Use items first-in-first-out (FIFO) Queue<T> Queue ConcurrentQueue<T>

ImmutableQueue<T>
使用数据后进先出 (LIFO)Use data Last-In-First-Out (LIFO) Stack<T> Stack ConcurrentStack<T>

ImmutableStack<T>
按顺序访问项Access items sequentially LinkedList<T> 无建议No recommendation 无建议No recommendation
删除集合中的项或向集合添加项时接收通知。Receive notifications when items are removed or added to the collection. (实现 INotifyPropertyChangedINotifyCollectionChanged(implements INotifyPropertyChanged and INotifyCollectionChanged) ObservableCollection<T> 无建议No recommendation 无建议No recommendation
已排序的集合A sorted collection SortedList<TKey,TValue> SortedList ImmutableSortedDictionary<TKey,TValue>

ImmutableSortedSet<T>
数学函数的一个集A set for mathematical functions HashSet<T>

SortedSet<T>
无建议No recommendation ImmutableHashSet<T>

ImmutableSortedSet<T>

TitleTitle 说明Description
选择集合类Selecting a Collection Class 描述不同的集合并帮助你为你的方案选择一个集合。Describes the different collections and helps you select one for your scenario.
常用的集合类型Commonly Used Collection Types 描述诸如 System.ArraySystem.Collections.Generic.List<T>System.Collections.Generic.Dictionary<TKey,TValue> 等常用泛型和非泛型集合类型。Describes commonly used generic and nongeneric collection types such as System.Array, System.Collections.Generic.List<T>, and System.Collections.Generic.Dictionary<TKey,TValue>.
何时使用泛型集合When to Use Generic Collections 讨论泛型集合类型的使用。Discusses the use of generic collection types.
集合内的比较和排序Comparisons and Sorts Within Collections 讨论在集合中使用等同性比较和排序比较。Discusses the use of equality comparisons and sorting comparisons in collections.
已排序的集合类型Sorted Collection Types 描述已排序集合的性能和特征Describes sorted collections performance and characteristics
哈希表和字典集合类型Hashtable and Dictionary Collection Types 描述泛型和非泛型基于哈希的字典类型的功能。Describes the features of generic and non-generic hash-based dictionary types.
线程安全集合Thread-Safe Collections 介绍支持从多个线程进行安全有效的并发访问的集合类型,例如 System.Collections.Concurrent.BlockingCollection<T>System.Collections.Concurrent.ConcurrentBag<T>Describes collection types such as System.Collections.Concurrent.BlockingCollection<T> and System.Collections.Concurrent.ConcurrentBag<T> that support safe and efficient concurrent access from multiple threads.
System.Collections.ImmutableSystem.Collections.Immutable 介绍不可变集合并提供各集合类型的链接。Introduces the immutable collections and provides links to the collection types.

参考Reference

System.Array
System.Collections
System.Collections.Concurrent
System.Collections.Generic
System.Collections.Specialized
System.Linq
System.Collections.Immutable