Pages

Friday, 12 April 2013

C# Dictionary: How to create and use Key / Value pairs in C# using Dictionary?

C# Dictionary: How to create and use Key / Value pairs in C# using Dictionary?

The Dictionary type provides fast lookups with keys to get values. With dictionary, we can use keys and values of any type, including ints and strings. Dictionary is used when we have many different elements. We specify its key type and its value type. It provides good performance.

The Dictionary instance is represented by a collection of key and value pairs. Dictionary is a generic class. This means it requires you to specify a type for it to use. So, you can use an int key, just as easily as a string key.

C# Program to add Key/Value to dictionary

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       Dictionary<string, int> dictionary = new Dictionary<string, int>();
       dictionary.Add("cat", 2);
       dictionary.Add("dog", 1);
       dictionary.Add("cow", 0);
       dictionary.Add("horse", -1);
    }
}

How to get values depending on the keys? How to check whether dictionary contains the desired value or not? Here is a simple program which will check and fetch the values corresponding to the keys.

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
      Dictionary<string, int> dictionary = new Dictionary<string, int>();
      dictionary.Add("crow", 1);
      dictionary.Add("cow", 5);
      // See whether Dictionary contains this string.
      if (dictionary.ContainsKey("crow"))
      {
         int value = dictionary["crow"];
         Console.WriteLine(value);
      }
      // See whether Dictionary contains this string.
      if (!dictionary.ContainsKey("cat"))
      {
       Console.WriteLine(false);
      }
   }
}

Output
1
False

Now lets try to fetch all the values of dictionary using foreach loop by storing dictionary in list.  We can use the Keys property and then look through each key and lookup the values. This method is slower but has the same results. Using the Keys collection and putting it in an array or List is effective. The Keys property returns a collection of type KeyCollection, not an actual List. We can convert it into a List.

using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       Dictionary<string, int> d = new Dictionary<string, int>()
       {
           {"cat", 2},
           {"dog", 1},
           {"cow", 0},
           {"horse", -1}
       };
      
       // Store keys in a List
       List<string> list = new List<string>(d.Keys);
       // Loop through list
       foreach (string k in list)
       {
          Console.WriteLine("{0}, {1}", k, d[k]);
       }
    }
}

Output
cat, 2
dog, 1
cow, 0
horse, -1

You can use the GetHashCode method and override it to create Dictionaries or hashes with the class. This can improve performance in those cases. A custom GetHashCode can influence performance.

No comments:

Post a Comment