C# Dictionary Tutorial For Beginners With Examples

A C# Dictionary is one of the most important and widely used collections classes. It consists of keys and corresponding values.
Dictionary<Tkey,Tvalue> is a generic class so the datatype of the keys and the values can be pre defined. Performance wise Dictionary objects are very efficient.

Initialize Dictionary object

Initialization of a Dictionary<Tkey,Tvalue> object can be done as shown below:
    Dictionary<string, string> dictFruits = new Dictionary<string, string>();
    
In the above example the dictionary object has a key of datatype string and value of datatype string.
The Dictionary generic class is part of System.Collections.Generic namespace.

Add items to C# Dictionary

To add items to a Dictionary object the Add method is used. Let us create a Dictionary object which contains name of fruits as its key and color of these fruits as its values.
    Dictionary<string, string> dictFruits = new Dictionary<string, string>();;

    dictFruits.Add("Guava", "Green");
    dictFruits.Add("Mango", "Yellow");
    dictFruits.Add("Grapes", "Red");

    Console.WriteLine("The color of Grapes is " + dictFruits["Grapes"]);

    Console.ReadLine();
    
Output: The color of Grapes is Red

Remove items from C# Dictionary

To remove items from a C# Dictionary the Remove method is used. The dictFruits dictionary object in previous example contains three items. If a key is removed from dictFruits dictionary of the previous example then the count becomes two.
    dictFruits.Remove("Grapes");
    Console.WriteLine("The Dictionary contains {0} elements", dictFruits.Count);

Output: The Dictionary contains 2 elements

Foreach loop to read values of a Dictionary object

Using a foreach loop is the easiest and fastest way to read all the keys and the corresponding values of a Dictionary object.
To do this, each of the elements of a Dictionary object should be accessed using a foreach loop. The retrieved values should then be stored in a KeyValuePair<TKey, TValue> object. From this then the keys and values can be read.
Below example will clear the explanation provided above. The earlier dictFruits Dictionary object has been used to explain this.
    foreach (KeyValuePair<string, string> kv in dictFruits)
    {
        Console.WriteLine("The key is {0} and value is {1}", kv.Key, kv.Value);
    }
    
Output: 
The key is Guava and value is green
The key is Mango and value is Yellow
The key is Grapes and value is Red

ContainsKey method to check if a key exists

To retrieve specific values, keys are used. However, there is a possibility that a specified key may not exist in a Dictionary object. In this case an KeyNotFound exception will be generated.
It is a good practice to check the availability of a key before trying to use it. The ContainsKey is used for this purpose.
    if (dictFruits.ContainsKey("Mango"))
        Console.WriteLine("Key exists");
    else
        Console.WriteLine("Key does not exists");
            
Output: Key exists

TryGetValue method to retrieve an item

If there is a possibility of a key not being present in a Dictionary object then the safest and efficient way to access such keys is to use a TryGetValue method.
If a key is not found then TryGetValue method returns falseand if found then true .
In our earlier example the dictFruits Dictionary object contained three keys GuavaMango andGrapes. In the below example we will try to access a key which does not exist and a key which exist.
    
    string value = string.Empty;
    bool result;

    result = dictFruits.TryGetValue("abc", out value);
    Console.WriteLine(result);

    result = dictFruits.TryGetValue("Mango", out value);
    Console.WriteLine(result);            

    Console.ReadLine();
        
Output: 
False
True

What about the value parameter in the above example?

If a key is not found then the value parameter will return the default value of the Dictionary element. In the above example it will be an empty string as the datatype of the Dictionary object is string.
If a key is found then the value parameter will return the actual value corresponding to the key.

A Sorted Dictionary object in C#

There is no sort method to order a Dictionary object. However, a Dictionary object can still be sorted by using a lambda expression.

Use Lambda expression

Lambda expressions can be used to sort a Dictionary object. As shown in the below example the Dictionary object dictFruits is ordered by its values.
   var result = dictFruits.OrderBy(x => x.Value);
   var result = dictFruits.OrderBy(x => x.Key);
        
To use a lambda expression System.Linq namespace should be used.
Although there are various other ways of sorting a Dictionary object. Using a Lambda expression is the most efficient one.

Use Generic SortedDictionary object

SortedDictionary<TKey,TValue> objects are Dictionary objects sorted by key. All the other behaviours of a SortedDictionary<TKey,TValue> object is same as a Dictionary<TKey,TValue> object.
    
    SortedDictionary<int, string> dictWeeks = new SortedDictionary<int, string>();

    dictWeeks.Add(3, "Monday");
    dictWeeks.Add(1, "Tuesday");
    dictWeeks.Add(2, "Wednesday");

    foreach (KeyValuePair<int, string> week in dictWeeks);
    {
        Console.WriteLine("The key is {0} and the value is {1}",week.Key,week.Value);
    }                       

    Console.ReadLine();
        
Output: 
The key is 1 and the value is Tuesday
The key is 2 and the value is Wednesday
The key is 3 and the value is Monday
In the above example, intentionally the keys were given in wrong order but after it was added to the SortedDictionary object the keys were automatically sorted.

Methods and Properties of a C# Dictionary

Commonly used methods of a Dictionary class are:
MethodDescription
AddThis method is used to add a key/value pair to a Dictionary object.
ClearRemoves all the elements from a Dictionary object.
ContainskeyChecks if a key is present in a Dictionary object.
ContainsValueChecks if a value is present in a Dictionary object.
RemoveRemoves a key/value pair with the matching key from a Dictionary object. Returns true if the element is found and removed or else returns false.
TryGetValueThis method tries to get the value of a specified key from a Dictionary object.
Commonly used properties of a Dictionary class are:
PropertyDescription
CountReturns the number of key/value pairs present in a Dictionary object.
ItemItem property is used to set or to get a value associated with a specified key from a Dictionary object.
KeysThis property is used to get all the keys present in a Dictionary object.
ValuesThis property is used to get all the values present in a Dictionary object.