How to Use C# Dictionaries - dummies

By John Paul Mueller, Bill Sempf, Chuck Sphar

You’ve no doubt used webster’s or another dictionary, but have you used a C# dictionary? Traditional dictionaries are organized as a bunch of words in alphabetical order. Associated with each word is a body of information including pronunciations, definitions, and other information. To use a dictionary, you look up a word and retrieve its information.

In C#, the dictionary “shape” differs from the list shape. Dictionaries are represented by the Dictionary<TKey, TValue> class. TKey represents the data type used for the dictionary’s keys (similar to the words in a standard dictionary or the terms you look up). TValue represents the data type used to store the information or data associated with a key (similar to the word’s definitions in webster’s).

Creating a dictionary

The first piece of the code just creates a new Dictionary object that has string keys and string values. You aren’t limited to strings, though. Either the key or the value, or both, can be any type. Note that the Add() method requires both a key and a value.

Dictionary<string, string> dict = new Dictionary<string, string>();

// Add(key, value).

dict.Add("C#", "cool");

dict.Add("C++", "like writing Sanskrit poetry in Morse code");

dict.Add("VB", "a simple but wordy language");

dict.Add("Java", "good, but not C#");

dict.Add("Fortran", "ancient");

dict.Add("Cobol", "even wordier and more verbose than VB");

Searching a dictionary

The ContainsKey() method tells you whether the dictionary contains a particular key. There’s a corresponding ContainsValue() method, too:

// See if the dictionary contains a particular key.

Console.WriteLine("Contains C# " + dict.ContainsKey("C#")); // True

Console.WriteLine("Contains Ruby " + dict.ContainsKey("Ruby")); // False

Dictionary pairs are in no particular order, and you can’t sort a dictionary. It really is just like a bunch of buckets spread around the floor.

Iterating a dictionary

You can, of course, iterate the dictionary in a loop just as you can in any collection. But keep in mind that the dictionary is like a list of pairs of items. Think of each pair as an object that contains both the key and the value. So to iterate the whole dictionary with foreach, you need to retrieve one of the pairs each time through the loop. The pairs are objects of type KeyValuePair<TKey, TValue>. This WriteLine() call uses the pair’s Key and Value properties to extract the items. Here’s what it looks like:

// Iterate the dictionary's contents with foreach.

// Note that you're iterating pairs of keys and values.

Console.WriteLine("\nContents of the dictionary:");

foreach (KeyValuePair<string, string> pair in dict)

{

// Because the key happens to be a string, we can call string methods on it.

Console.WriteLine("Key: " + pair.Key.PadRight(8) + "Value: " + pair.Value);

}

The following code snippet shows how to iterate just the keys or just the values. The dictionary’s Keys property returns another collection: a list-shaped collection of type Dictionary<TKey, TValue>.KeyCollection. Because the keys happen to be strings, you can iterate the keys as strings and call string methods on them. The Values property is similar. The final bit of code uses the dictionary’s Count property to see how many key/value pairs it contains.

// List the keys, which are in no particular order.

Console.WriteLine("\nJust the keys:");

// Dictionary<TKey, TValue>.KeyCollection is a collection of just the

// keys,in this case strings. So here’s how to retrieve the keys:

Dictionary<string, string>.KeyCollection keys = dict.Keys;

foreach(string key in keys)

{

Console.WriteLine("Key: " + key);

}

// List the values, which are in same order as key collection above.

Console.WriteLine("\nJust the values:");

Dictionary<string, string>.ValueCollection values = dict.Values;

foreach (string value in values)

{

Console.WriteLine("Value: " + value);

}

Console.Write("\nNumber of items in the dictionary: " + dict.Count);

Of course, that doesn’t exhaust the possibilities for working with dictionaries. Look up generic dictionary in C# Language Help for all the details.