Dictionary
A series of key-value pairs.
Object
–> Dictionary<TKey, TValue>
Type safe. Invalid key throws exception.
NamespaceSystem.Collections.Generic
ImplementsIDictionary<TKey, TValue>
Items in a dictionary are instances of a struct.
Other Dictionaries
SortedDictionary<TKey, TValue>
A collection of key/value pairs that are sorted by key.
Construction`
Dictionary<key-type, value-type> d = new();
// or
Dictionary<TKey, TValue> d = new()
{
{ key1, value1 }
…
};
Accessing
d[key]
Iterating
foreach (KeyValuePair<TKey, TValue> item in d)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
Methods
Manipulating
.Add(key, value);
.Add(key: k, value: v);
Searching
.ContainsKey(key) // Return boolean if key is in dictionary.
.ContainsValue(value) // Return boolean if value is in dictionary.
.TryGetValue(key, out var1) // Retrieve value at key and store it in var1.
Properties
.CountReturn
number of k:v pairs.
.KeysReturn
the keys.
.ValuesReturn
the values.