The Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.
Note: |
|---|
| The speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey. |
As long as an object is used as a key in the Dictionary, it must not change in any way that affects its hash value. Every key in a Dictionary must be unique according to the dictionary's equality comparer. A key cannot be a null reference (Nothing in Visual Basic), but a value can be, if the value type TValue is a reference type.
Dictionary requires an equality implementation to determine whether keys are equal. You can specify an implementation of the IEqualityComparer generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic equality comparer EqualityComparer.Default is used. If type TKey implements the System.IEquatable generic interface, the default equality comparer uses that implementation.
Note: |
|---|
| For example, you can use the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys. |
The capacity of a Dictionary is the number of elements the Dictionary can hold. As elements are added to a Dictionary, the capacity is automatically increased as required by reallocating the internal array.
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. The order in which the items are returned is undefined.
The foreach statement of the C# language (for each in C++, For Each in Visual Basic) requires the type of each element in the collection. Since the Dictionary is a collection of keys and values, the element type is not the type of the key or the type of the value. Instead, the element type is a KeyValuePair of the key type and the value type. For example:
|
foreach (KeyValuePair<int, string> kvp in myDictionary) {...}
|
|
for each (KeyValuePair<int, String^> kvp in myDictionary) {...}
|
|
For Each kvp As KeyValuePair(Of Integer, String) In myDictionary
...
Next kvp
|
The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it.
Note: |
|---|
| Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method. |