The Dictionary<(Of <(TKey, TValue>)>) 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<(Of <(TKey, TValue>)>) 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<(Of <(TKey, TValue>)>), it must not change in any way that affects its hash value. Every key in a Dictionary<(Of <(TKey, TValue>)>) must be unique according to the dictionary's equality comparer. A key cannot be nullNothingnullptra null reference (Nothing in Visual Basic), but a value can be, if the value type TValue is a reference type.
Dictionary<(Of <(TKey, TValue>)>) requires an equality implementation to determine whether keys are equal. You can specify an implementation of the IEqualityComparer<(Of <(T>)>) generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic equality comparer EqualityComparer<(Of <(T>)>)..::.Default is used. If type TKey implements the System..::.IEquatable<(Of <(T>)>) 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<(Of <(TKey, TValue>)>) is the number of elements the Dictionary<(Of <(TKey, TValue>)>) can hold. As elements are added to a Dictionary<(Of <(TKey, TValue>)>), 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<(Of <(TKey, TValue>)>) 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<(Of <(TKey, TValue>)>) 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 <(TKey, TValue>)>) 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.
|