Dictionary Examples

What is a Dictionary

Well a Dictionary is a common Data Structure, this data contained is a collection of key-value paired items. Dictionaries are based on hash tables, so it makes them fast, certainly faster than Lists (Just because Dictionaries are faster than Lists, doesn't mean that Lists shouldn't be used, it all depends on the purpose and usage). The main difference between a Dictionary and a Hashtable is Dictionaries specify its types and Hashtables don't. This type safety makes Dictionaries faster than standard Hashtable's, as there is no type casting going on.

Create a Dictionary

To use the Dictionary class, you must declare its namespace, by using the "using" keyword. "System.Collections.Generic"

using System.Collections.Generic

The syntax for declaring a new Dictionary using int for the key and string for the value type. (You can always use the var keyword to declare a Dictionary)

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

Code Example:

using System.Collections.Generic;

namespace GetCoding
{
  class Program
  {
    static void Main()
    {
      // Create Dictionary - int -> key, string -> value
      Dictionary<int, string> myDictionary = new Dictionary<int, string>();
    {
  }
}

Please note that there is nothing to stop you from using Lists as you dictionary value if required e.g:

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

But for now we will keep to basic string as value for simplicity!

Adding items to Dictionary

To add to your Dictionary we will need to use the Add method, which takes two parameters. First being the unique key and the second being the data or value you want to store.

myDictionary.Add(0,"First item");

Alternatively you could use an indexer to add to your dictionary, it doesn't matter which way you choose to add elements to your dictionary as it does the same thing. I would recommend using the Add method as it makes it very clear what you code is doing.

// using indexer '[0]' to add.
myDictionary[0] = "First item";

The final method you can use to add items to your dictionary is by using collection initializer, this basically involves creating a Dictionary and add items on creation. Please note that extra items can be added using the Add method.

Dictionary<int, string> myDictionary2 = new Dictionary<int, string>
{
  {0, "First item"},
  {1, "Second item"}
};

It is ideal to always use collection initializer where possible and add extra items later if required. Collection initializer always make the code look cleaner and easy to read. Situations where you can't use this, for example if you need to add an item based upon a condition, then you must use the Add method.

Code Example:

using System.Collections.Generic;

namespace GetCoding
{
  class Program
  {
    static void Main()
    {
      // Create Dictionary - int -> key, string -> value
      Dictionary<int, string> myDictionary = new Dictionary<int, string>();

      // Adding to myDictionary using Add method
      myDictionary.Add(0,"First item");
      myDictionary.Add(1,"Second item");
      myDictionary.Add(2,"Third item");

      // Adding to myDictionary using indexer
      myDictionary[3] = "Forth item";
      myDictionary[4] = "Fifth item";

      // Create myDictionary2, adding items using collection initializer
      Dictionary<int, string> myDictionary2 = new Dictionary<int, string>
      {
        {0, "First item"},
        {1, "Second item"},
        {2, "Third item"},
        {3, "Forth item"},
        {4, "Fifth item"}
      };
    }
  }
}

What we need to remember is that if you try to add an item to a dictionary, the key must be unique otherwise an error will occur.
Code Example:

using System.Collections.Generic;

namespace GetCoding
{
  class Program
  {
    static void Main()
    {
      // Create Dictionary - int -> key, string -> value
      Dictionary<int, string> myDictionary = new Dictionary<int, string>();

      // Adding to myDictionary using Add method
      myDictionary.Add(0, "First item");
      myDictionary.Add(1, "Second item");
      myDictionary.Add(2, "Third item");
      // This is ok because value can be the same, but key must be unique
      myDictionary.Add(3, "Third item");

      // Adding to myDictionary using key thats already been added
      myDictionary.Add(2, "Forth item");
     }
   }
}

The error(Exception) is shown below, high-lighting where the error actually occurred:

dictionary add error

Removing items from Dictionary

Just like being able to add to a dictionary, we must also be able to remove items. When removing items there are really only two ways you can do this, either by clearing all items at once or remove a single item at a time.

First we will start off by removing all elements from a dictionary. There are two ways of doing this, we can either the the Clear() method or  assign a new dictionary to the variable.

// Clearing all elements
myDictionary.Clear();

or

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

These essentially produce the same result but internally they work differently. Now you may not actually want to remove all of the elements, you may only need to remove one of them. You will need to use the Remove() method. This method requires the key of the element you want to be removed otherwise it will throw an error(No overload for method 'Remove' takes 0 arguments) when you try to compile(build) your code.

Code Example:

using System.Collections.Generic;

namespace GetCoding
{
  class Program
  {
    static void Main()
    {
      // Create myDictionary, adding items using collection initializer
      Dictionary<int, string> myDictionary = new Dictionary<int, string>
      {
        {0, "First item"},
        {1, "Second item"},
        {2, "Third item"},
        {3, "Forth item"},
        {4, "Fifth item"}
      };
      // Remove element by key, "Second item"
      myDictionary.Remove(1); 
    }
  }
}

Don't worry if you try to remove an element that doesn't exist, it just wont do anything or throw an error. E.g.

myDictionary.Remove(5);

As we know element 5 does not exist in the Dictionary, trying to remove it wont affect the dictionary or even trow an exception, it will just continue as nothing has happened. 

Using a C# Dictionary

Well you can use a dictionary in different ways, for example you can count how many items a dictionary has or even reassign a element with a new value. There are also methods which tells you if an element exists dependent on its key.