C# Dictionary

In c#, Dictionary is a generic type of collection, and it is used to store a collection of key/value pairs organized based on the key. The dictionary in c# will allow to store only the strongly-typed objects, i.e., the key/value pairs of the specified data type.

 

In c#, while storing the elements in the dictionary object, you need to make sure that the keys are unique because the dictionary object will allow us to store duplicate values, but the keys must be unique.

 

The size of the dictionary object will vary dynamically so that you can add or remove elements from the dictionary based on our requirements.

 

In c#, the dictionary object is same as the hashtable object, but the only difference is the dictionary object is used to store a key-value pair of same data type elements.

C# Dictionary Declaration

In c#, the dictionary is a generic type of collection, and it is provided by System.Collections.Generic namespace.

 

As discussed, the collection is a class, so to define a dictionary, you need to declare an instance of a dictionary class before performing any operations such as add, delete, etc. like as shown below.

 

Dictionary<TKey, TValue> dct = new Dictionary<TKey, TValue>();

If you observe the above dictionary declaration, we created a generic dictionary (dct) with an instance of dictionary class using type parameters (TKey, TValue) as placeholders with angle (<>) brackets.

 

Here, the angle (<>) brackets will indicate that the dictionary is a generic type and type parameter TKey represents a type of keys to be accepted by the dictionary, and TValue is used to represent a type of values to be accepted by the dictionary.

 

In c#, the generic dictionary (Dictionary<T>) is an implementation of IDictionary<TKey, TValue> interface, so we can also use IDictionary<TKey, TValue> interface to create an object of the generic dictionary (Dictionary<TKey, TValue>) like as shown below.

 

IDictionary<TKey, TValue> dct = new Dictionary<TKey, TValue>();

C# Dictionary Initialization

Following is the example of initializing a generic dictionary by specifying a required type for key and value.

 

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

If you observe the above example, we defined a dictionary (dct) with the required key and value types to store. Here, the dictionary object will store a key of string type and value of int type.

C# Dictionary Properties

The following are some of the commonly used properties of dictionary objects in the c# programming language.

 

PropertyDescription
Count It is used to get the number of key/value pair elements in the dictionary.
Item[TKey] It is used to get or set the value associated with the specified key.
Keys It is used to get a collection of keys in the dictionary.
Values It is used to get a collection of values in the dictionary.

C# Dictionary Methods

The following are some of the commonly used methods of the generic dictionary to perform add, search, insert, delete or sort operations in the c# programming language.

 

MethodDescription
Add It is used to add elements to the dictionary object with a specified key and value.
Clear It will remove all the keys and values from the Dictionary<TKey, TValue>.
ContainsKey It is used to determine whether the specified key exists in Dictionary<TKey, TValue> or not.
ContainsValue It is used to determine whether the specified value exists in Dictionary<TKey, TValue> or not.
Remove It is used to remove an element from Dictionary<TKey, TValue> with the specified key.
TryGetValue It is used to get the value associated with the specified key.

C# Add Elements to Dictionary

As discussed, while adding elements to the dictionary object, we need to make sure that there will not be any duplicate keys.

 

Following is the example of adding key/value pair elements to dictionary objects in different ways.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          //Create a new dictionary with int keys and string values.
          Dictionary<int, string> dct = new Dictionary<int, string>();
          // Add elements to the dictionary object.
          // No duplicate keys allowed but values can be duplicate
          dct.Add(1, "Suresh");
          dct.Add(4, "Rohini");
          dct.Add(2, "Trishi");
          dct.Add(3, null);
          // Another way to add elements.
          // If key not exist, then that key adds a new key/value pair.
          dct[5] = "Trishi";
          // Add method throws exception if key already in dictionary
          try
          {
             dct.Add(2, "Praveen");
          }
          catch (ArgumentException)
          {
             Console.WriteLine("An element with Key = '2' already exists.");
          }
          Console.WriteLine("*********Dictionary1 Elements********");
          // Accessing elements as KeyValuePair objects.
          foreach (KeyValuePair<int, string> item in dct)
          {
             Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
          }

          // Creating and initializing dictionary
          Dictionary<string, int?> dct2 = new Dictionary<string, int?> {
                                              {"msg2", 1},
                                              {"msg3", 20},
                                              {"msg4", 100},
                                              {"msg1", null}
                                          };
          Console.WriteLine("*********Dictionary2 Elements********");
          // Accessing elements as KeyValuePair objects.
          foreach (KeyValuePair<string, int?> item in dct2)
          {
             Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
          }
          Console.ReadLine();
       }
    }
}

If you observe the above example, we are able to define a new generic dictionary (dct, dct2) collections by using System.Collections.Generic namespace. Here, we added only the defined data type keys and values to the newly created dictionaries (dct, dct2) in different ways.

 

As discussed, the Add method will throw an exception if we try to add a key (2) that is already existing, so to handle that exception, we used a try-catch block.

 

When you execute the above c# program, you will get the result as shown below.

 

C# Add Elements to Dictionary Object Example Result

 

If you observe the above result, we got an exception when we tried to add a key (2) that is already existing and added a key (5) that is not existing in the dictionary.

C# Access Dictionary Elements

In c#, we have different ways to access dictionary elements, i.e., either using index positions or by iterating through the list using for / foreach loops.

 

Following is the example of accessing dictionary elements in different ways.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          //Create a new dictionary
          Dictionary<int, string> dct = new Dictionary<int, string>();
          dct.Add(1, "Suresh");
          dct.Add(4, "Rohini");
          dct.Add(2, "Trishi");
          dct.Add(3, "Praveen");
          // Access value with key (not index)
          string val1 = dct[2];
          string val2 = dct[3];
          string val3 = dct[4];
          Console.WriteLine("******Access Elements with Keys*****");
          Console.WriteLine("Value at Key '2': " + val1);
          Console.WriteLine("Value at Key '3': " + val2);
          Console.WriteLine("Value at Key '4': " + val3);
          Console.WriteLine("*********Access Elements with Foreach Loop********");
          foreach (KeyValuePair<int, string> item in dct)
          {
             Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
          }
          Console.WriteLine("*********Dictionary Keys********");
          foreach (var item in dct.Keys)
          {
             Console.WriteLine("Key = {0}", item);
          }
          Console.WriteLine("*********Dictionary Values********");
          foreach (var item in dct.Values)
          {
              Console.WriteLine("Value = {0}", item);
          }
          Console.ReadLine();
       }
    }
}

If you observe the above example, we are accessing dictionary elements in different ways by using keys and foreach loops based on our requirements.

 

When you execute the above c# program, you will get the result as shown below.

 

C# Access Dictionary Object Elements Example Result

C# Remove Elements from Dictionary

In c#, by using the Remove() method, we can delete a key/value pair from the dictionary object.

 

Following is the example of deleting elements from the dictionary object in the c# programming language.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          //Create a new dictionary
          Dictionary<int, string> dct = new Dictionary<int, string>();
          dct.Add(1, "Suresh");
          dct.Add(4, "Rohini");
          dct.Add(2, "Trishi");
          dct.Add(3, "Praveen");
          dct.Add(5, "Sateesh");
          // Remove element with key (not index)
          dct.Remove(3);
          dct.Remove(5);
          Console.WriteLine("*********Access Dictionary Elements********");
          Console.WriteLine();
          foreach (KeyValuePair<int, string> item in dct)
          {
             Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
          }
          Console.ReadLine();
       }
    }
}

If you observe the above example, we used a Remove() method to delete a particular key of elements from the dictionary.

 

When you execute the above c# program, we will get the result as shown below.

 

C# Remove Elements from Dictionary Object Example Result

C# Dictionary Check If Item Exists

By using ContainsKey() and ContainsValue() methods, we can check whether the specified key / value element exists in dictionary or not. In case if it exists, these methods will return true otherwise false.

 

Following is the example of using ContainsKey() and ContainsValue() methods to check for an item that exists in a dictionary or not in c#.

 

using System;
using System.Collections.Generic;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          //Create a new dictionary
          Dictionary<int, string> dct = new Dictionary<int, string>();
          dct.Add(1, "Suresh");
          dct.Add(4, "Rohini");
          dct.Add(2, "Trishi");
          dct.Add(3, "Praveen");
          dct.Add(5, "Sateesh");
          Console.WriteLine("Contains Key 2: {0}", dct.ContainsKey(2));
          Console.WriteLine("Contains Value 'Tutlane': {0}", dct.ContainsValue("Tutlane"));
          Console.ReadLine();
       }
    }
}

If you observe the above example, we used a ContainsKey() and ContainsValue() methods to check for particular keys and values that exist in the dictionary (dct) or not.

 

When you execute the above c# program, you will get the result as shown below.

 

Contains Key 2: True

Contains Value 'Tutlane': False

C# Dictionary (Dictionary<TKey, TValue>) Overview

The following are the important points that need to remember about the dictionary in c#.

 

  • Dictionary is used to store a collection of key/value pairs that are organized by key.
  • Dictionary will allow us to store duplicate values, but keys must be unique to identify the values in the dictionary.
  • In a dictionary, the keys cannot be null, but the values can be null.
  • You can access dictionary elements either by using keys or with a foreach loop. In the foreach loop, you need to use KeyValuePair<TKey, TValue> to get key/value pairs from the Dictionary object.

Difference between Dictionary and Hashtable in C#

The following are the main differences between hashtable and dictionary in c# programming language.

 

  • Hashtable is a non-generic type of collection so that it can store elements of different data types, but Dictionary is a generic type of collection so that it can store elements of the same data type.
  • Hashtable is available with System.Collections namespace, but the dictionary is available with System.Collections.Generic namespace.
  • In the foreach loop, you need to use the DictionaryEntry property to get the key/value pair from a hashtable, but we need to use the KeyValuePair property to access key/value pair elements from the dictionary.
  • When compared with dictionary object, the hashtable will provide a lower performance because the hashtable elements are of object type, so the boxing and unboxing process will occur when we store or retrieve values from the hashtable.
  • In c#, the hashtable will throw an error if we try to find a key that does not exist, but the dictionary object will return null in case the defined key not exists.