Thursday, April 17, 2008

Dictionary - Collection

The Dictionary is class that can hold a collection of strongly typed key value pairs.
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Mark Moeykens");
dictionary.Add(2, "Jake Agee");
// Will add "Rich Talbot" if indexer (3) not found.
dictionary[3] = "Rich Talbot";

string person = dictionary[3]; // Rich Talbot
In this example I made the key an int and the value a string.

Not all the time will you know if a key exists when you look up a value in your Dictionary. Two ways you can go about trying to get a name:
string name;
if (dictionary.TryGetValue(4, out name))
    name = "Found: " + name;
else
    name = "No name found.";
TryGetValue method returns true if the key is found and puts the found value into the "name" variable in this case.
string name2;
if (dictionary.ContainsKey(4))
    name2 = "Found: " + dictionary[4];
else
    name2 = "No name found.";
This example just checks to see if it exists and then gets the value on a seperate line if true.

More Info: MSDN: Dictionary<TKey, TValue> Generic Class