An array of C#, PHP, and HTML programming articles, tutorials, and resources

Using C# Dictionary Collection

by Victor | November 19, 2008 | In C#

A Dictionary object in C# has become one of my recent favorites. Below are a few important aspects:

  1. Requires including System.Collections.Generic;
  2. Each entry in a Dictionary is a KeyValuePair (consisting of two objects: key and value)
  3. The key must be unique
  4. The value does not need to be unique
  5. Both the key and value can be any object (string, int, custom class, etc…)
  6. Retrieving a value via a key take close to O(1) time
  7. The order of a KeyValuePair enumeration is not defined

Next is an example of how to create and initialize a Dictionary object. Our Dictionary will have an integer and as a key and a string as a value.

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

Now that we have our Dictionary datatype, we will add two values to the Dictionary. Note that at this point, intellisense knows the two expected types.

myDictionary.Add(1, "Victor");
myDictionary.Add(2, "Billy");

Finally, deleting an object is just as easy:

myDictionary.Remove(1);

And these are the basics to using a Dictionary collection!

One Response »

  1. [...] from a previous post on Using C# Dictionary Collection, the next most common tasks is enumerate through every element in the Dictionary. To begin, each [...]

Leave a Reply