C# Dictionary

In c#, Dictionary is a generic type of collection and it is used to store a collection of key / value pairs that are 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 specified data type.

 

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

 

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

 

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

C# Dictionary Declaration

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

 

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

 

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

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

 

Here, the angle (<>) brackets will indicate that the dictionary is a generic type and type parameter TKey is to represent a type of keys to be accepted by dictionary and TValue is used to represent a type of values to be accepted by 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 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 above example, we defined a dictionary (dct) with 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

Following are the some of commonly used properties of dictionary object in c# programming language.

 

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

C# Dictionary Methods

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

 

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

C# Add Elements to Dictionary

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

 

Following is the example of adding a key/value pair elements to dictionary object 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 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, Add method will throw an exception in case if we try to add a key (2) which is already existing so to handle that exception we used a try-catch block.

 

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

 

C# Add Elements to Dictionary Object Example Result

 

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

C# Access Dictionary Elements

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

 

Following is the example of accessing a 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 above example, we are accessing dictionary elements in different ways by using keys and foreach loops based on our requirements.

 

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

 

C# Access Dictionary Object Elements Example Result

C# Remove Elements from Dictionary

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

 

Following is the example of deleting an elements from the dictionary object in 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 above example, we used a Remove() method to delete a particular key of element from the dictionary.

 

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

 

C# Remove Elements from Dictionary Object Example Result

In case, if you want to remove all the elements from sorted list, then use Clear() method.

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 exists in 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 above example, we used a ContainsKey() and ContainsValue() methods to check for a particular keys and values exists in dictionary (dct) or not.

 

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

 

Contains Key 2: True

Contains Value 'Tutlane': False

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

Following are the important points which needs to be remember about 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 a duplicate values but keys must be unique to identify the values in dictionary.
  • In dictionary, the keys cannot be null but the values can be null.
  • We can access dictionary elements either by using keys or with foreach loop. In foreach loop we need to use KeyValuePair<TKey, TValue> to get a key/value pairs from Dictionary object.

Difference between Dictionary and HashTable in C#

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

 

  • Hashtable is a non-generic type of collection so it can store an elements of different data types but Dictionary is a generic type of collection so it can store an elements of same data type.
  • Hashtable is available with System.Collections namespace but the dictionary is available with System.Collections.Generic namespace.
  • In foreach loop, we need to use DictionaryEntry property to get the key/value pair from hashtable but we need to use KeyValuePair property to access key/value pair elements from 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 a values from hashtable.
  • In c#, the hashtable will throw an error if we try to find a key which does not exists but the dictionary object will return null in case the defined key not exists.