Generic Collection Type Dictionary in C# with examples

In this article, we’ll discuss the Generic Collection Type<TKey, Tvalue> dictionary in C# with examples. A Dictionary class is the structure of data that is used to express a group of data pairs with keys and values. We shall learn about the features, benefits, applications, and real-world coding implementations of the generic collection-type dictionary at the end of this article.


Dictionary<TKey, TValue> Class in C# :


A dictionary is a generic collection that can be used to store key/value pairs in C#. Dictionary operates quite similarly to non-generic hashtables. The distinction is that we must specify the type for both the keys and the values when building the generic dictionary object and the advantage of a Dictionary is, it is a generic type. The dictionary's size automatically increases when more entries are added to the generic DictionaryTKey, TValue> collection due to its dynamic nature. The dictionary class is defined under the namespace System.Collections.Generic.


Create Dictionary in C#:


The Dictionary class contains several constructors that are used to generate the Dictionary, and we can use each of them to create an instance of the Dictionary class. Here we will only use the Dictionary<TKey, TValue>() constructor.


Dictionary<TKey, TValue>(): The Dictionary() constructor is used to create an instance of the Dictionary class that is empty and has the default initial capacity. Let's see how to use the Dictionary() in c# to create an instance of the Dictionary class.

Step 1:

The System.Collections.Generic namespace must be imported before the Dictionary class can be used in your program.

using System.Collections.Generic;

step 2:

Now the next step is, We  have to create an instance of the Dictionary<TKey, TValue> class using the Dictionary() constructor as follows:

Dictionary<string, string> dict_name = new Dictionary<string,string>();

This is the way to create a dictionary constructor. The class is defined in the code to create a dictionary with string types for both the keys and the values.


Add new item in Dictionary in C#:


Use the Add() method to add key/value pairs to our Dictionary if we want to add new elements.

Add(string key, string value): An element with the supplied key and value can be added to the Dictionary using the Add(TKey key, TValue value) method. The element to be added's key is specified by the parameter key, and its value is specified by the parameter value in this case. For a reference type, the Key cannot be null, but the value can.

Below is an example of Add() method to add elements to the Dictionary.


Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


namespace MyDictionary

{

    internal class Program

    {

        static void Main(string[] args)

        {


            Dictionary<string, string> myDict = new Dictionary<string, string>();


            // Adding elements to dictionary using Add() method.


            myDict.Add("America", "you live in America");

            myDict.Add("India", "you live in India");

            myDict.Add("U.k", "you live in  U.K");

            myDict.Add("Newzealand", "you live in Newzealand ");

            myDict.Add("South Africa", "you live in SouthAfrica");


            Console.WriteLine(myDict["America"]); // to get single value we use index to pass keys.



           

            // By using foreach loop we can access all the key elements of our data bu using ' Keys '.

            foreach (var key in myDict.Keys)

            {

            

                Console.WriteLine(key);

            }




            // By using foreach loop we can access all the values elements of our data b using ' Values '.

            foreach (var key in myDict.Values)

            {


                Console.WriteLine(key);

            }


           


           // By using foreach loop we can access all the data by using ' KeyValuePair<> ' class.

            foreach(KeyValuePair<string, string> item in myDict)

            {

                Console.WriteLine("key is:" + item.Key + " Value is:" + item.Value);

            }



            Console.ReadLine();

        }

    }

}


Here we will get the result of all coding implementations as shown below.


Output:

you live in America



America

India

U.k

Newzealand

South Africa



you live in America

you live in India

you live in  U.K

you live in Newzealand

you live in SouthAfrica



key is:America Value is:you live in America

key is:India Value is:you live in India

key is:U.k Value is:you live in  U.K

key is:Newzealand Value is:you live in Newzealand

key is:South Africa Value is:you live in SouthAfrica



TryAdd(TKey,TValue) : This method defines true when the key and value are successfully added to the dictionary; and it is used to define ‘false when the dictionary already contains the specified key, in which case nothing gets added.

Below is an example of the TryAdd() method to add elements to the Dictionary.

Example :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


namespace MyDictionary

{

    internal class Program

    {

        static void Main(string[] args)

        {


           

            var dictionary = new Dictionary<string, int>();


            // add the string with value 1.

            bool result = dictionary.TryAdd("Hello World", 1);

            Console.WriteLine("Added: " + result);



           // the value already exists, so we cannot add it again.

            bool result1 = dictionary.TryAdd("Hello World", 1);

            Console.WriteLine("Added: " + result1);



            // the value is still 1.

            Console.WriteLine(dictionary.GetValueOrDefault("Hello World"));




            Console.ReadLine();


        }

    }

}


Here is the output for all the implementations.

Output :

Added: True

Added: False

1



Search any item in Dictionary in C# :


The following methods of the Generic Dictionary Collection Class in C# can be used to determine whether a key/value pair is present in the Dictionary collection or not.

ContainsKey(TKey key): To determine whether a key is present in the dictionary or not, use the Dictionary's ContainsKey(TKey key) method. The Dictionary object's parameter key to finding it. It will return true if the supplied key is found in the collection; else, it will return false.

ContainsValue(TValue value):
To determine whether a value is contained in the dictionary or not, use the Dictionary class's ContainsValue(TValue value) method. The value of the parameter to find in the Dictionary object. It will return true if the supplied value is included in the collection; otherwise, it will return false.

Below is an example of both methods.

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;


namespace MyDictionary

{

    internal class Program

    {

        static void Main(string[] args)

        {


            Dictionary<string, string> myDict = new Dictionary<string, string>();


            // Adding elements to dictionary using Add() method.

            myDict.Add("America", "you live in America");

            myDict.Add("India", "you live in India");

            myDict.Add("U.k", "you live in  U.K");

            myDict.Add("Newzealand", "you live in Newzealand ");

            myDict.Add("South Africa", "you live in SouthAfrica");


            //Checking the key using the ContainsKey method


            // ----- Contains Key ------


            // Check whether Dictionary contains this (key) string or not.

            if (myDict.ContainsKey("Newzealand"))

            {

                var key = myDict["Newzealand"];

                Console.WriteLine("\nIs America Key Exists : " + key);

            }



            // This is another way to check whether Dictionary contains (key) string or not.

            Console.WriteLine("\nIs America Key Exists : " + myDict.ContainsKey("America"));

            Console.WriteLine("Is India Key Exists : " + myDict.ContainsKey("India"));



            // ----- Contains Value -------


            // Check whether Dictionary contains this (value) string or not.

            if (myDict.ContainsValue("you live in America"))

            {

               

                Console.WriteLine("\nCongrats you are from America ");

            }




            // This is another way to check whether Dictionary contains (key) string or not.


            Console.WriteLine("\nIs America Key Exists : " + myDict.ContainsValue("you live in America"));

            Console.WriteLine("Is India Key Exists : " + myDict.ContainsValue("you live in India"));



            Console.ReadLine();


        }

    }

}


Output:

Is America Key Exists : you live in Newzealand


Is America Key Exists : True

Is India Key Exists : True


Congrats you are from America


Is America Key Exists : True

Is India Key Exists : True



Update any item to Dictionary in C# :


An existing key-value pair in the Dictionary collection in C# can be updated using the key indexer. Please look at the example below for a better understanding.

When updating the elements in a dictionary, we must define the key and value for each pair of words. The key information is provided in square brackets. Below is a list of the syntax.

dictionary[key] = value;

For a better understanding, please have a look at the following example.

Example:

using System;

using System.Collections.Generic;


namespace MyDictionary

{

    internal class Program

    {

        static void Main(string[] args)

        {


            Dictionary<string, string> myDict = new Dictionary<string, string>();


            // Adding elements to dictionary using Add() method.

            myDict.Add("America", "you live in America");

            myDict.Add("India", "you live in India");

            myDict.Add("U.k", "you live in  U.K");

            myDict.Add("Newzealand", "you live in Newzealand ");

            myDict.Add("South Africa", "you live in SouthAfrica");



           //Updating dictionary by key America and India using Indexer.

            myDict["America"] = "you live in America and you're American";

            myDict["India"] = "you live in India and you're Indian";


            Console.WriteLine("\nAfter Updating the Key America and India");

            Console.WriteLine($"America: {myDict["America"]}");

            Console.WriteLine($"India: {myDict["India"]}");




            //Update a Dictionary (This is another approach to update)

            if (myDict.ContainsKey("India"))

            {

                myDict.Remove("India");

                myDict.Add("India", " you are the citizen of India");

                Console.WriteLine(myDict["India"]);

            }


            Console.ReadLine();


        }

    }

}


Output:

After Updating the Key America and India

America: you live in America and you're American

India: you live in India and you're Indian


you are the citizen of India



Delete any item in Dictionary in C#:


Use the following Remove method of the Dictionary collection class to remove an element from the dictionary.

Remove(TKey key): The entry with the supplied key is removed from the Dictionary collection using this method. Here, the element to remove is specified by the parameter key. Use the ContainsKey() method to see if the supplied key already exists in the Dictionary before removing it as it will produce a KeyNotfoundException if it is not.


The Dictionary class in C# has a Clear function, which must be used if you wish to delete every element from the Dictionary collection.


Clear(): The Dictionary object can have all of its elements, and all of its keys, and values removed using this method.


Please look at the example below for a better understanding of how to utilize the Remove and Clear method of the Generic Dictionary collection class.


Example:

using System;

using System.Collections.Generic;


namespace MyDictionary

{

    internal class Program

    {

        static void Main(string[] args)

        {


            Dictionary<string, string> myDict = new Dictionary<string, string>();


            // Adding elements to dictionary using Add() method.

            myDict.Add("America", "you live in America");

            myDict.Add("India", "you live in India");

            myDict.Add("U.k", "you live in  U.K");

            myDict.Add("Newzealand", "you live in Newzealand ");

            myDict.Add("South Africa", "you live in SouthAfrica");



           

            Console.WriteLine($"Dictionary Elements Count Before Removing: {myDict.Count}");


            foreach (KeyValuePair<string, string> item in myDict)

            {

                Console.WriteLine("key is:" + item.Key + " Value is:" + item.Value);

            }




            // Remove element U.k from Dictionary Using Remove() method

            if (myDict.ContainsKey("U.k"))

            {

                myDict.Remove("U.k");

                Console.WriteLine($"\nDictionary Elements Count After Removing U.k: {myDict.Count}");

                foreach (var item in myDict)

                {

                    Console.WriteLine($"Key:{item.Key}, Value:{item.Value}");

                }

            }




            // Remove all Elements from Dictionary Using Clear method

            myDict.Clear();

            Console.WriteLine($"\nDictionary Elements Count After Clear: {myDict.Count}");



            Console.ReadLine();


        }

    }

}



Output:


Dictionary Elements Count Before Removing: 5

key is:America Value is:you live in America

key is:India Value is:you live in India

key is:U.k Value is:you live in  U.K

key is:Newzealand Value is:you live in Newzealand

key is:South Africa Value is:you live in SouthAfrica



Dictionary Elements Count After Removing U.k: 4

Key:America, Value:you live in America

Key:India, Value:you live in India

Key:Newzealand, Value:you live in Newzealand

Key:South Africa, Value:you live in SouthAfrica



Dictionary Elements Count After Clear: 0



This was the whole process of the Dictionary class in C# to get the proper concepts with practical implementations.


Conclusion:


The value in a dictionary can be null, but not the key. The key and dictionary must be distinct. If you try to utilize a duplicate key, the compiler will throw an exception because it is not permitted. You can only store the same types of components in a dictionary. The number of elements that a dictionary can store is referred to as its capacity.

The Dictionary Generic Collection class is present in System.Collections.Generic namespace. The fastest way to find a value in a dictionary is by using the keys.

I genuinely hope you enjoyed reading this article and found something useful. Comment below with your thoughts and recommendations.







Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee