Using C# Dictionary Collection

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!

Share and Enjoy:
  • Digg
  • DotNetKicks
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • MySpace
  • Netvibes
  • Reddit
  • StumbleUpon
You can leave a response, or trackback from your own site.

2 Responses to “Using C# Dictionary Collection”

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

  2. tesfay aregawi says:

    i want to include one dictionary file to the program it self instead of using one by one……………..
    please help me
    this is my final project

Leave a Reply