A Dictionary object in C# has become one of my recent favorites. Below are a few important aspects:
- Requires including
System.Collections.Generic; - Each entry in a Dictionary is a KeyValuePair (consisting of two objects: key and value)
- The key must be unique
- The value does not need to be unique
- Both the key and value can be any object (string, int, custom class, etc…)
- Retrieving a value via a key take close to O(1) time
- 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!





[...] 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 [...]