As we all know, the general dictionary has two languages. one act as a key and another one as value. eg: In English, to Hindi dictionary, if you are looking for the meaning of delete in Hindi.

then Delete becomes the key and the meaning of Delete in Hindi becomes the value for that

Dictionary as key-value pair

What is Dictionary in C#?

The C# Dictionary <TKey, TValue> is a generic collection that stores key-value pairs in no particular order. It’s a part of the System.Collections.Generic namespace in .Net Framework.

What is Dictionary in C#
Initialize Dictionary in C#

Features of Dictionary<TKey, Tvalue>

  • In C# Dictionary<Tkey, Tvalue>, Null and duplicate keys are not allowed. However, It can hold the null values against any key.
  • It can store only similar kinds of data types.

Interfaces Implemented by Dictionary

  • Dictionary implementers the IDictionary<TKey,TValue> Interface.
  • IReadOnlyCollection<KeyValuePair<TKey,TValue>> Interface which is inherited from the IReadOnlyDictionary<TKey,TValue> Interface.
  • IDictionary Interface which is inherited from the ICollection interface

Frequently Used Methods in C# Dictionary

MethodDetails
AddAdds the specified key and value to the dictionary.
Throw, ArgumentNullException – the key is null. ArgumentException: An element with the same key already exists in the Dictionary.
TryAddAttempts to add the specified key and value to the dictionary. Returns, true if the key/value pair was added to the dictionary successfully; otherwise, false.
ContainsKeyDetermines whether the Dictionary contains the specified key. Returns, true if the Dictionary contains an element with the specified key; otherwise, false.
ContainsValueDetermines whether the Dictionary contains the specified value. Returns, true if the Dictionary contains an element with the specified key; otherwise, false.
RemoveRemoves the value with the specified key from the Dictionary. Returns: true if the element is successfully found and removed; otherwise, false. This method returns false if the key is not found in the Dictionary.
ClearRemoves all keys and values from the Dictionary.
TrimExcessSets the capacity of this dictionary to hold up a specified number of entries without any further expansion of its backing storage.
EnsureCapacityEnsures that the dictionary can hold up to a specified number of entries without any further expansion of its backing storage.
TryGetValueIt gets the value associated with the specified key. true if the Dictionary contains an element with the specified key; otherwise, false.

Is the Size of the C# Dictionary Fixed?

No, It’s Not. It is dynamic in nature, which means that the dictionary’s size grows in response to demand.

How to Initialize Dictionary in C#?

Dictionary in C# support 7 constructors that can be used for creating the object as per the use case.

Dictionary object with default constructor and string as key and value.

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

Initialize Dictionary using the list of key-value pairs.

     var list = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("key1", "value1"),
                new KeyValuePair<string, string>("key2", "value2"),
            };
            var dictionary = new Dictionary<string, string>(list);

Dictionary has a constructor that takes the custom implementation of the IEqualityComparer. In case you want to introduce the custom behavior of comparing the object by implementing the IEqualityComparer.

In this case, we are initializing the dictionary with string key and value. So, we need the custom implementation of IEqualityComparer<string>.

   public class CustomStringComparer : IEqualityComparer<string>
    {
        public bool Equals(string x, string y)
        {
            return x?.ToLower() == y?.ToLower();
        }

        public int GetHashCode(string obj)
        {
            return obj.GetHashCode();
        }
    }
    
    static class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>(new CustomStringComparer());
            Console.ReadKey();
        }

    }

Initialize Dictionary in C# with the initial capacity and custom compare.

Without IEqualityComparer
var dictionary = new Dictionary<string, string>(2);

With IEqualityComparer
var dictionary = new Dictionary<string, string>(2,new CustomStringComparer());

Constructor overloads with a capacity are used when you know what number of items to expect better than the class.

For example, if you create a collection of 30 values and know that this number will never change, you can initialize the collection with a capacity of 30, preventing it from having to resize if the default capacity is lower.

How C# Dictionary is resized?

If you are not sure about the initial capacity of the dictionary collection. You can use the default constructor of the dictionary.

Let’s write some piece of code to add the key-value pair into the dictionary object. We have a key-value pair assignment inside the infinite loop. that will keep adding the random GUID as a key and value in the dictionary.

  var dictionary = new Dictionary<string, string>();
            while (true)
            {
                Console.WriteLine("Number of Keys in Dictionary: " + dictionary.Count);
                Console.WriteLine("Capacity of Dictionary: "+dictionary.EnsureCapacity(0));
                Console.ReadKey();
                dictionary.Add(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
             }

Also, it will print the numbers of keys in the dictionary and the capacity of the dictionary using the EnsureCapacity method.

Let’s see the output once we run this program.

Complete Guide on C# Dictionary | 2022 1
The capacity of Dictionary Object at runtime

As we see when the dictionary had no item, the default capacity was zero. ASA we added the first item into the dictionary, and the capacity becomes three.

Keep adding the items and once you will try to add the fourth item in the dictionary the capacity of the dictionary will be double the current capacity multiplied by two plus some number.

ASA we added the eight-item in the dictionary, and the capacity of the dictionary becomes seventeen. Which is double the last capacity of 7*2+some number.

Not sure about the exact formula for increasing the capacity of the dictionary. However, the formula goes like this.

Capacity= CurrentCapacity*2+SomeNumber

Add Items into the Dictionary

As seen in the above table, there are two methods available to add items to the dictionary using Add and TryAdd method.

Add items at the time of initialization.

   var dictionary = new Dictionary<string, string>
            {
                { "A", "A" },
                { "a", "a" }
            };

Add items using Add method. When you try to add the null or duplicate key the exception will be thrown.

            var dictionary = new Dictionary<string, string>
            {
                { "A", "A" },
                { "a", "a" }
            };
            dictionary.Add("Name","Deependra");
            dictionary.Add("Website","beetechnical.com");

ArgumentNullException when we try to add the null as a key in the dictionary.

  var dictionary = new Dictionary<string, string>();
  dictionary.Add(null,"Deependra");
ArgumentNullException in C# Dictionary
ArgumentNullException in C# Dictionary

ArgumentException when we try to add the same key multiple times.

  var dictionary = new Dictionary<string, string>();
  dictionary.Add("Name","Deependra");
  dictionary.Add("Name","Advit");
ArgumentException in C# Dictionary
ArgumentException in C# Dictionary

Add items using the TryAdd method. This can be useful when we don’t want to throw the runtime exception in case of duplicate keys.

In case of a duplicate key, this method will not throw the Argument exception rather it will not add the item and return false.

 static class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>();
            var added = dictionary.TryAdd("Name", "John");
            if (added == true)
            {
                Console.WriteLine("Added Successfully");
            }
            Console.ReadLine();
        }
Add Item using the TryAdd method in C# Dictionary
Add Item using the TryAdd method in C# Dictionary
 static class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>();
            var added = dictionary.TryAdd("Name", "John");
            var addedDuplicateKey = dictionary.TryAdd("Name", "John");
            if (addedDuplicateKey == true)
            {
                Console.WriteLine("Added Successfully");
            }else
            {
                Console.WriteLine("Failed to add item");
            }
            Console.ReadLine();
        }
Failed Adding item into the dictionary using the TryAdd method
Failed Adding item into the dictionary using the TryAdd method

Note: TryAdd method will throw the ArgumentNullException If you try to add the null as a key in the dictionary.

Reading Dictionary Items in C#

Read using the index method in Dictionary. In case the key is not found, the KeyNotFound Exception will be thrown.

  static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("Name", "Deependra");
            dictionary.Add("Company", "Maersk Logistics");
            var company = dictionary["Company"];
            Console.WriteLine(company);
//Output will be 
    //Maersk Logistics

//Read using non existing key
        var company = dictionary["CompanyName"];
            Console.WriteLine(company);
//Output will be the Runtime exception
            Console.ReadLine();
        }
KeyNotFound Exception While Reading Dictionary in C#
KeyNotFound Exception While Reading Dictionary in C#

Read value from the dictionary using the TryGetValue method in C#.

    static class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("Name", "Deependra");
            dictionary.Add("Company", "Maersk Logistics");
            var company = dictionary.TryGetValue("Company", out var companyValue) ? companyValue : "Not Found";
            Console.WriteLine(company);
            var companyNameValue = dictionary.TryGetValue("CompanyName", out var value) ? value : "Not Found";
            Console.WriteLine(companyNameValue);         
            Console.ReadLine();
        }

    }
Find Dictionary Value using the TryGetValue method in C#
Find Dictionary Value using the TryGetValue method in C#

We can also read the dictionary key and values using the .Net LINQ framework. Let’s see a few examples.

static class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("Name", "Deependra");
            dictionary.Add("Company", "Maersk Logistics");

            Console.WriteLine(dictionary.Values.FirstOrDefault());
            //Print the first item in the dictionary

            Console.WriteLine(dictionary.Values.LastOrDefault());
            //Print the last item in the dictionary

            Console.WriteLine(dictionary.FirstOrDefault(x=>x.Key=="Name").Value);
            //Print the value where key is name
            
            Console.ReadLine();
        }

    }
Read Dictionary using Linq in C#
Read Dictionary using Linq in C#

Iterate over a dictionary in C#

I’ve seen a few different ways to iterate over a dictionary in C#. It completely depends on the use case, and what exactly you want to iterate through the read.

We can use foreach to iterate over the dictionary in C# and read the key and value.

     static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("Name", "Deependra");
            dictionary.Add("Company", "Maersk Logistics");
            dictionary.Add("Country", "India");
            dictionary.Add("City", "Bangalore");

            foreach (KeyValuePair<string, string> keyValuePair in dictionary)
            {
                Console.WriteLine( keyValuePair.Key+":"+keyValuePair.Value);
            }

            Console.ReadLine();
        }
Complete Guide on C# Dictionary | 2022 2
dictionary using foreach in C#

Read only keys or values using the foreach in C#.

 static class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("Name", "Deependra");
            dictionary.Add("Company", "Maersk Logistics");
            dictionary.Add("Country", "India");
            dictionary.Add("City", "Bangalore");

            //Read all keys in the dictionary
            foreach (var key in dictionary.Keys)
            {
                Console.WriteLine(key);
            }


            //Read all the values in the dictionary
            foreach (var value in dictionary.Values)
            {
                Console.WriteLine(value);
            }

            Console.ReadLine();
        }

    }
Read keys and values using foreach
Read keys and values using foreach

Loop through dictionary object and read the data using for loop in C#. ElementAt method provided by the Linq framework can be used to read the dictionary object using an index.

static class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("Name", "Deependra");
            dictionary.Add("Company", "Maersk Logistics");
            dictionary.Add("Country", "India");
            dictionary.Add("City", "Bangalore");
            for (int i = 0; i < dictionary.Count; i++)
            {
                var dictionaryObject = dictionary.ElementAt(i);
                Console.WriteLine(dictionaryObject.Key + ":" + dictionaryObject.Value);
            }

            Console.ReadLine();
        }

    }

Remove Items from Dictionary in C#

There are two methods available in the dictionary to remove the elements “Remove” and Clear.

  • Remove A method used for removing the specific key-value pairs by using the key.
  • Clear: Used for removing all the key-value pairs available in the dictionary.
    static class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("Name", "Deependra");
            dictionary.Add("Company", "Maersk Logistics");
            dictionary.Add("Country", "India");
            dictionary.Add("City", "Bangalore");

//Remove the element of the dictionary using the provided key
            dictionary.Remove("Name");
            dictionary.Remove("Company");

//Try to remove the item using the wrong key
            dictionary.Remove("WrongKey");  //throws run-time exception: KeyNotFoundException

//So, before removing the data using key,validate the key
           if (dictionary.ContainsKey("WrongKey"))
            {
                dictionary.Remove("WrongKey");
            }


//Clear the dictionary object
            dictionary.Clear();

            Console.ReadLine();
        }

    }

It’s always a good practice to validate the key before removing it from the dictionary. Else, you might end up in the KeyNotFound exception.

How to Sort C# Dictionary?

We can Sort any kind of collection with the help of methods exposed by Linq library in C#. Order by can be used to sort the collection.

 static class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, int>()
            {
                { "Deep", 32 },
                { "Saurabh", 30 },
                { "Rahul", 35 },
                { "Jitendra", 24 }
            };

            foreach (var keyValuePair in dictionary)
            {

                Console.WriteLine(keyValuePair.Key + " " + keyValuePair.Value);
            }
            
            //After sorting
            Console.WriteLine("\nAfter sorting\n");
            var sortedDictionary = dictionary.OrderBy(x => x.Value);
            foreach (var keyValuePair in sortedDictionary)
            {
                Console.WriteLine(keyValuePair.Key + " " + keyValuePair.Value);
            }

            //After sorting
            Console.WriteLine("\nAfter Sorting in Descending Order\n");
            var sortedDictionaryInDescOrder = dictionary.OrderByDescending(x => x.Value);
            foreach (var keyValuePair in sortedDictionaryInDescOrder)
            {
                Console.WriteLine(keyValuePair.Key + " " + keyValuePair.Value);
            }
            Console.ReadKey();
        }

    }
Sort Dictionary in C#
Sort Dictionary in C#

When to use Dictionary vs ConcurrentDictionary c#?

The main benefit of using ConcurrentDictionary over the standard Dictionary is thread safety. If your application will have multiple threads using the same dictionary at the same time, you will need the thread-safe ConcurrentDictionary, especially if these threads will be writing to or building the dictionary.

No one stops you from using the ConcurrentDictionary in the single-threaded applications as well. The downside to using ConcurrentDictionary without multi-threading is overhead.

All those functions that allow it to be thread-safe will still be there, and all the locks and checks will still happen, taking processing time and using extra memory.

Dictionary vs Hashtable In C#

The hashtable is a loosely-typed data structure, so you can add keys and values of any type to it. The values stored in the hashtable need boxing and unboxing, which has a minor impact on performance. There is no order maintained by the hashtable.

A Dictionary is a generic class ( Dictionary<TKey, TValue> ) so that accessing its content is type-safe (i.e. you do not need to cast from an Object, as you do with a Hashtable).

static class Program
    {
        static void Main(string[] args)
        {
            var hashtable = new Hashtable();
            hashtable.Add("Name", "Deependra");
            hashtable.Add("Age", 30);
            hashtable.Add("FullName", new { FirstName = "Deependra", LastName = "Kushwaha" });

            foreach (DictionaryEntry dictionaryEntry in hashtable)
            {
                Console.WriteLine($"{dictionaryEntry.Key} : {dictionaryEntry.Value}");
            }

            Console.ReadKey();
        }

    }

As seen in the above example, there is no restriction in the datatype for the value stored against each key in the hashtable.

Every time you try to access the elements of the hashtable. you will receive in diffrent-2 orders.

  • Complete Guide on C# Dictionary | 2022 3
  • Complete Guide on C# Dictionary | 2022 4
  • Complete Guide on C# Dictionary | 2022 5

Conclusion

So in this post, we have tried understanding the C# dictionary class. What is this and when to use this along with some examples of the different operations which can be performed in the dictionary class.

We have also seen the alternatives available for dictionary like concurrentdictionary and hashtable.

Hope this complete guide of C# dictionary was useful to you, Follow us for more blogs like this.

83 / 100

Comments

No comments yet. Why don’t you start the discussion?