Archive for the ‘Code Library’ Category

C# Dictionaries for Dummies

Wednesday, November 4th, 2009

How to use C# Dictionaries

In a nutshell:

Dictionaries can be used to store a list of items, but instead of using a standard flat “List” you can identify the records with a key.

First of all, make sure you’ve included the correct namespace:

using System.Collections.Generic;

Secondly you need to declare a dictionary.

For this example we are going to declare a dictionary called dicEmployees and within the dictionary we are going to store the identity number of the employee as well as their name.

Dictionary<int, string> dicEmployees = new Dictionary<int, string>();

Populating the Dictionary

Populating the dictionary is as easy as one-two-three…

dicEmployees.Add(14, “Marcus Orelius”);

In this case we’ve added Marcus Orelius with employee number 14 to our dictionary.

Retrieving Dictionary Values

Retrieving values are just as easy…

string sEmployeeName = dicEmployees[14];

Additional Options:

dicEmployees.ContainsKey(14); // Returns true/false; if the dictionary contains the key 14

dicEmployees.ContainsValue(”Marcus Orelius”); // Returns true/false; if the dictionary contains the value “Marcus Orelius”

dicEmployees.Count; // Returns the total item count in the dictionary (int)

dicEmployees.Keys; // Returns the “KeyCollection” list of the keys currently in the dictionary

dicEmployees.Values; // Returns a “ValueCollection” list of the values currently in the dictionary

Playing It Safe…

I highly recommend building in a safeguard when checking the values of a dictionary:

if(dicEmployees.ContainsKey(14))

return dicEmployees[14];

Dictionary of Dictionaries:

I recently tried a dictionary of dictionaries and was quite happy with the result. Let’s build on the previous example. Assume you want to store a list of years and include if Marcus ever took leave in those years. We are going to declare a dictionary of a dictionary which will enable us to store a list of employees and the years they worked plus if they ever went on leave…

Dictionary<int, Dictionary<int, bool>> dicEmployees = new Dictionary<int, Dictionary<int, bool>>();

Dictionary<int, bool> dicMarcus = new Dictionary<int, bool>();

//Add years and if Marcus ever took leave on those days

dicMarcus.Add(41, true);
dicMarcus.Add(42, true);
dicMarcus.Add(43, false);
dicMarcus.Add(44, true);
dicMarcus.Add(45, false);

dicEmployees.Add(14, dicMarcus);

//Did Marcus take leave when he was 43?

bool wasMarcusAtWorkAged43 = dicEmployees[14][43];

// Value returned is false

Hope that helps…