Open In App

C# Dictionary with examples

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is grows according to the need. Important Points:

How to create the Dictionary?

Dictionary class has 7 constructors which are used to create the Dictionary, here we only use Dictionary<TKey, TValue>() constructor and if you want to learn more about constructors then refer C# | Dictionary Class. Dictionary<TKey, TValue>(): This constructor is used to create an instance of the Dictionary<TKey, TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type as follows: Step 1: IncludeSystem.Collections.Generic namespace in your program with the help of using keyword. Syntax:



using System.Collections.Generic; 

Step 2: Create a Dictionary using Dictionary<TKey, TValue> class as shown below:

Dictionary dictionary_name = new Dictionary();

Step 3: If you want to add elements in your Dictionary then use Add() method to add key/value pairs in your Dictionary. And you can also add key/value pair in the dictionary without using Add method. As shown in the below example. Step 4: The key/value pair of the Dictionary is accessed using three different ways:






for(int x=0; x< My_dict1.Count; x++)
{
    Console.WriteLine("{0} and {1}", My_dict1.Keys.ElementAt(x),
                         My_dict1[ My_dict1.Keys.ElementAt(x)]);
}




Console.WriteLine("Value is:{0}", My_dicti[1123]);
Console.WriteLine("Value is:{0}", My_dicti[1125]);

Example: 




// C# program to illustrate how
// to create a dictionary
using System;
using System.Collections.Generic; 
 
class GFG {
 
        // Main Method
    static public void Main () {
         
        // Creating a dictionary
        // using Dictionary<TKey,TValue> class
        Dictionary<int, string> My_dict1 = 
                       new Dictionary<int, string>();
           
          // Adding key/value pairs
          // in the Dictionary
          // Using Add() method
          My_dict1.Add(1123, "Welcome");
          My_dict1.Add(1124, "to");
          My_dict1.Add(1125, "GeeksforGeeks");
           
          foreach(KeyValuePair<int, string> ele1 in My_dict1)
          {
              Console.WriteLine("{0} and {1}",
                        ele1.Key, ele1.Value);
          }
          Console.WriteLine();
           
          // Creating another dictionary
          // using Dictionary<TKey,TValue> class
      // adding key/value pairs without
          // using Add method
      Dictionary<string, string> My_dict2 = 
              new Dictionary<string, string>(){
                                  {"a.1", "Dog"},
                                  {"a.2", "Cat"},
                                {"a.3", "Pig"} };
          
          foreach(KeyValuePair<string, string> ele2 in My_dict2)
          {
              Console.WriteLine("{0} and {1}", ele2.Key, ele2.Value);
          }
    }
}

Output:
1123 and Welcome
1124 and to
1125 and GeeksforGeeks

a.1 and Dog
a.2 and Cat
a.3 and Pig

How to remove elements from the Dictionary?

In Dictionary, you are allowed to remove elements from the Dictionary. Dictionary<TKey, TValue> class provides two different methods to remove elements and the methods are:

Example: 




// C# program to illustrate how
// remove key/value pairs from
// the dictionary
using System;
using System.Collections.Generic; 
 
class GFG {
 
        // Main Method
    static public void Main() {
         
        // Creating a dictionary
        // using Dictionary<TKey,TValue> class
        Dictionary<int, string> My_dict = 
                     new Dictionary<int, string>();
           
          // Adding key/value pairs in the
          // Dictionary Using Add() method
          My_dict.Add(1123, "Welcome");
          My_dict.Add(1124, "to");
          My_dict.Add(1125, "GeeksforGeeks");
           
          // Before Remove() method
          foreach(KeyValuePair<int, string> ele in My_dict)
          {
              Console.WriteLine("{0} and {1}",
                          ele.Key, ele.Value);
          }
          Console.WriteLine();
           
          // Using Remove() method
          My_dict.Remove(1123);
           
          // After Remove() method
          foreach(KeyValuePair<int, string> ele in My_dict)
          {
              Console.WriteLine("{0} and {1}",
                          ele.Key, ele.Value);
          }
          Console.WriteLine();
           
           
          // Using Clear() method
          My_dict.Clear();
           
          Console.WriteLine("Total number of key/value "+
           "pairs present in My_dict:{0}", My_dict.Count);
         
    }
}

Output:
1123 and Welcome
1124 and to
1125 and GeeksforGeeks

1124 and to
1125 and GeeksforGeeks

Total number of key/value pairs present in My_dict:0

How to check the availability of elements in the Dictionary?

In Dictionary, you can check whether the given key or value present in the specified dictionary or not. The Dictionary<TKey, TValue> class provides two different methods for checking and the methods are:

Example: 




// C# program to illustrate how
// to  check the given key or
// value present in the dictionary
// or not
using System;
using System.Collections.Generic; 
 
class GFG {
 
        // Main Method
    static public void Main () {
         
                 // Creating a dictionary
        // using Dictionary<TKey,TValue> class
        Dictionary<int, string> My_dict = 
                      new Dictionary<int, string>();
           
          // Adding key/value pairs in the
          // Dictionary Using Add() method
          My_dict.Add(1123, "Welcome");
          My_dict.Add(1124, "to");
          My_dict.Add(1125, "GeeksforGeeks");
           
          // Using ContainsKey() method to check
          // the specified key is present or not
          if (My_dict.ContainsKey(1122)==true)
          {
              Console.WriteLine("Key is found...!!");
          }
 
          else
          {
               Console.WriteLine("Key is not found...!!");
          }
           
          // Using ContainsValue() method to check
          // the specified value is present or not
          if (My_dict.ContainsValue("GeeksforGeeks")==true)
          {
              Console.WriteLine("Value is found...!!");
          }
 
          else
          {
               Console.WriteLine("Value is not found...!!");
          }
    }
}

Output:
Key is not found...!!
Value is found...!!

Article Tags :
C#