20 - Dictionaries
Dictionaries are another alternative to using Lists and arrays. Dictionaries add an additional key field which can be used to reference an object. This additional key field gives a dictionary what is called a key/value pair. It allows items to be searched for either by key or value. It is important when designing dictionaries to give them meaningful keys with the values. Keys and values can be any type, but there can only be one instance of each key. This is the opposite for values in which you can have the same value for many keys.
The definition for a dictionary is similar to how you define lists or arrays. The only difference is that you will be initializing with a key and a value rather than just a value.
Implementation is also very similar to implementing arrays and lists. Again, you are adding a key and a value. Remember that you cannot add multiple keys to a dictionary. You can use multiple values though.
Adding elements is again very similar to adding items in lists. Just make sure the key type and the value type are equal.
You can also remove elements by removing them with a key. In our example we can remove the element "Bob" by using the Remove(<Key>) method.
We can also count the number of elements in the dictionary by using the .Count property.
There are a few ways to access elements in a dictionary. Dictionaries are not like lists and arrays where an indexer will suffice to access them. A key must be given to get the corresponding value.
Changing elements will be similar to how we accessed them. We simply use the key with the name to change the value stored.
There are a ton more things that you can do with keys including sorting and some math with specialized versions of dictionaries. Click on this link to see all of the things that you can do with dictionaries in C#.