Collections

Dictionaries

A dictionary is another popular collection type, and it is a little different to a list. A dictionary allows you to specify a key type as well as the value type.

using System; using System.Collections.G...

A dictionary is a data structure that allows you to add an item, and refer to it through a key. When you declare a dictionary, you need to provide 2 generic type arguments:

Dictionary<string, bool> people = new Dictionary<string, bool>();

This is similar to the List<T>, but the generic type of the dictionary is Dictionary<TKey, TValue>.

You can use any type for both type arguments, so for instance:

Dictionary<Person, DateTime> birthdays = new Dictionary<Person, DateTime>();
Dictionary<Point, string> locations = new Dictionary<Point, string>();

You can also substitute the var keyword much like any other declaration:

var droids = new Dictionary<string, Droid>();

You can also initialise a dictionary and provide values:

Dictionary<string, int> ages = new Dictionary<string, int> { { "Luke", 53 }, { "Leia", 53 } };

Under the hood

Unlike lists, dictionaries don't use an array as the backing source. A dictionary uses a structure known as a hashtable. In a hashtable, to store a value (or to retrieve a value), a number known as a hashcode is generated for the key that you provide. That hashcode is used as the index in an internal array of the hashtable which actually stores the value.

The idea behind this concept is that when you have obtained a hashcode, its far simpler to look up the target value, rather than iterate through the table to identify the key manually.

In the .NET Dictionary, the hashcode provides the index for a "bucket". The bucket array is a pre-allocated size, and may be grown as items are added and it reaches capacity. The bucket stores the index of the actual value in an "entries" array.

Accessing list values

To access a value from the list, you use the same "index" notation we've seen previously, but instead of using a number, you use value of the same type as the 'Key' type argument:

var droids = new Dictionary<string, Droid>() { { "R2 D2", new Droid() } };
Droid r2d2 = droids["R2 D2"];

If you provide a key that doesn't exist, you'll get a KeyNotFoundException thrown.

Adding dictionary values.

To add an item to the dictionary, there are two options, the first of which is using the Add method:

droids.Add("R2 D2", new Droid());

Using the Add method does have a caveat - if you are adding an item with a key that already exists in the dictionary, it will throw an ArgumentException stating that the key already exists in the dictionary. Alternatively, you can use the index notation to set the value:

droids["R2 D2"] = new Droid();

This method allows you to replace existing items without an exception being thrown.

Removing values

To remove an item from a dictionary, you need to use the Remove method:

droids.Remove("R2 D2");

Again, by specifying the key, you can remove the value. The Remove method will return a value (a boolean) indicating whether the item was removed:

if (droids.Remove("R2 D2"))
{
    Console.WriteLine("Removed R2 D2");
}
else
{
    Console.WriteLine("Couldn't find R2 D2");    
}

Iterating through a dictionary

Much like the list, dictionaries support enumeration. The big difference between them is that where List returns an enumeration of the type T, the Dictionary<TKey, TValue> type will return an enumeration of the type KeyValuePair<TKey, TValue> which is a tuple of the key and value for each item. So, using the same for-each loop we've seen previously, we can move through the array:

foreach (var pair in droids)
{
    Console.WriteLine("Found: " + pair.Value + ", with key: " + pair.Key);    
}

 

Page 12 of 31