Learn to program in Visual Basic .NET, the right way

Collections - Dictionary(Of TKey, TValue)

What are Dictionary(Of TKey, TValue)s?

Dictionary(Of TKey, TValue), which from this point forward I will refer to as "Dictionary" or "Dictionaries", are dynamic collections used to store zero or more KeyValuePairs that are the same data type.

Just like Lists, Dictionaries reside in the System.Collections.Generic namespace.

The T in TKey and TValue refers to the data type that the collection will store.

KeyValuePairs

KeyValuePairs are unique in that they are a single item, but they store two values. The Key portion of the KeyValuePair is unique in that there cannot be more than one item in a Dictionary that share the same Key. The Value portion of the KeyValuePair is not unique and there can be more than one item in a Dictionary that share the same Value.

The example used in the array lesson was the English alphabet. This is because in the alphabet, there are only 26 letters.

The example used in the List lesson was a garage. This is because garages allow for vehicles to come and go.

Think of a Dictionary like a restaurant menu. Menus will not have the same item twice, but some items may be the same price. Also a restaurant may add or remove items based on how well or poor they are selling.

Class

Dictionaries are just like Lists in that they are a class. The following demonstrates how to initialize a Dictionary:

Fiddle: Live Demo

Add Values

There is one built-in methods of adding values to a Dictionary:

The Add method will add one value to the end of the collection. The following demonstrates how to add a value to a Dictionary using the Add method:

Fiddle: Live Demo

Remove Values

There is one built-in methods of removing values from a Dictionary:

The Remove method will remove one value from the collection by the item's Key. The following demonstrates how to remove a value from a Dictionary:

Fiddle: Live Demo

Get Values

Unlike Lists, with Dictionaries to get a value, you get the Value by its Key. The following demonstrates how to get a value from a Dictionary by its Key:

Fiddle: Live Demo

Exception

If you try to get or remove a Value, but the specified Key does not exists within the Dictionary, then you will get a KeyNotFoundException.

If you are unsure of if the Key exists within the Dictionary, then it is best to use a conditional statement and the ContainsKey method to ensure that the Key exists.