C# Generic Dictionary

A generic dictionary in C# stores data in key and value pairs. Unlike a generic list, where items are accessible using their numeric index value, items in a dictionary are accessible via their key, which can be of any data type. In the most basic dictionary, there is no order to the items within it, due to the absence of an index value, however, there is a special type of dictionary, called a sorted dictionary, where items are sorted based on the key. Again, the values stored in a dictionary can be of any C# data type.

Below is an example of a dictionary, called ‘people’, where the key is a string, that holds a person’s name and the value is an integer for their age.

Dictionary<string, int> people = new Dictionary<string, int>();
people.Add("Bob Smith", 30);
people.Add("George Jones", 21);
people.Add("Fred Bloggs", 43);
people.Add("Alan White", 29);

The first line declares the dictionary, with a string for the key and an integer for the value. Four key and value pairs are then added to the dictionary using its ‘Add’ method, with a person’s name as the key and their age as the value.

The declaration and initialisation can be combined into one statement, so the above could be re-written as follows.

Dictionary<string, int> people = new Dictionary<string, int>()
{
    {"Bob Smith", 30},
    {"George Jones", 21},
    {"Fred Bloggs", 43},
    {"Alan White", 29}
};

It is possible to see how many key and value pairs there are in the dictionary using the ‘Count’ property of the dictionary itself.

Console.WriteLine(people.Count);

As with other collections, it is possible to loop through a dictionary using a ‘foreach’ loop. Here, the key and value for each person are incorporated in to a sentence stating a person’s age. The curly braces that contain a number are placeholders for the key and value of the dictionary.

foreach (KeyValuePair<string, int> person in people)
{
    Console.WriteLine("{0} is {1} years old.", person.Key, person.Value);
}

The output in the console from the above example is as follows.

Bob Smith is 30 years old.
George Jones is 21 years old.
Fred Bloggs is 43 years old.
Alan White is 21 years old.

It is also possible to access a single value if the key is known.

Console.WriteLine(people["Bob Smith"]);

Dictionaries share the flexibility of generic lists with the ease of adding, updating and removing key and value pairs. Here a key of ‘John Smith’, with a value of ‘52’ is added to the ‘people’ dictionary.

people.Add("John Smith", 52);

Note that if the key ‘John Smith’ already exists, then an error will be produced. To stop this from happening the ‘ContainsKey’ dictionary method could be used to check to see if the key already exists before adding it.

if (!people.ContainsKey("John Smith"))
{
    people.Add("John Smith", 52);
}

To update a value in a dictionary, the dictionary name and key need to be specified.

people["Bob Smith"] = 100;

Note that if the key specified doesn’t already exist, then this has the same effect as using the dictionary ‘Add’ method, where a new key and value pair are added to the dictionary.

Removing a key and value pair from a dictionary is simply a matter of using the ‘Remove’ method and specifying the key.

people.Remove("George Jones");

Finally, if it is necessary to remove all items in a dictionary in one go, instead of individually with the ‘Remove’ method, there is a ‘Clear’ method to accomplish this.

people.Clear();

Further Reading