|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Selecting a Collection Class
Be sure to choose your System.Collections class carefully. Using the wrong type can restrict your use of the collection.
Consider the following questions:
Do you need a sequential list where the element is typically discarded after its value is retrieved?
Do you need to access the elements in a certain order, such as FIFO, LIFO, or random?
Do you need to access each element by index?
The Hashtable, SortedList, ListDictionary, and StringDictionary classes, and the Dictionary<TKey, TValue> and SortedDictionary<TKey, TValue> generic classes offer access to their elements by the key of the element.
The NameObjectCollectionBase and NameValueCollection classes, and the KeyedCollection<TKey, TItem> and SortedList<TKey, TValue> generic classes offer access to their elements by either the zero-based index or the key of the element.
Will each element contain one value, a combination of one key and one value, or a combination of one key and multiple values?
One value with embedded key: Use the KeyedCollection<TKey, TItem> generic class.
One key and multiple values: Use the NameValueCollection class.
Do you need to sort the elements differently from how they were entered?
The Hashtable class sorts its elements by their hash codes.
The SortedList class and the SortedDictionary<TKey, TValue> and SortedList<TKey, TValue> generic classes sort their elements by the key, based on implementations of the IComparer interface and the IComparer<T> generic interface.
ArrayList provides a Sort method that takes an IComparer implementation as a parameter. Its generic counterpart, the List<T> generic class, provides a Sort method that takes an implementation of the IComparer<T> generic interface as a parameter.
Do you need fast searches and retrieval of information?
Do you need collections that accept only strings?
In addition, you can use any of the generic collection classes in the System.Collections.Generic namespace as strongly typed string collections by specifying the String class for their generic type arguments.
LINQ to Objects enables developers to use LINQ queries to access in-memory objects as long as the object type implements IEnumerable or IEnumerable<T>. LINQ queries provide a common pattern for accessing data, are typically more concise and readable than standard foreach loops, and provide filtering, ordering, and grouping capabilities. In addition, LINQ queries can also provide performance improvements. For more information, see LINQ to Objects.