Mastering C# Dictionary : The Ultimate Guide for 2023

C# Dictionary is a collection type in the C# programming language that stores key-value pairs. It is similar to a physical dictionary, where each word is associated with a definition. In a C# Dictionary, the keys and values can be of any data type, as long as the key is unique within the dictionary.

Dictionary as key-value pair

Dictionaries are useful when you need to quickly lookup a value based on its corresponding key. They provide fast access to data and can improve the performance of your code when used correctly.

What is Dictionary in C#?

C# Dictionaries are part of the System.Collections.Generic namespace and can be instantiated using the Dictionary<TKey, TValue> class, where TKey is the data type of the keys, and TValue is the data type of the values.

What is Dictionary in C#
Initialize Dictionary in C#

Features of Dictionary<TKey, Tvalue>

The Dictionary<TKey, TValue> class in C# provides several features that make it a powerful collection type.

Here are some of its key features:

  1. Key-value pairs: A Dictionary<TKey, TValue> stores data as key-value pairs, where each key is unique and associated with a specific value.
  2. Fast lookup: Dictionaries provide fast access to values based on their keys, even with large amounts of data.
  3. Dynamic size: The size of a Dictionary<TKey, TValue> can grow or shrink dynamically as new elements are added or removed.
  4. Indexing: You can access values in a Dictionary<TKey, TValue> using the index notation, such as myDictionary[key].
  5. Enumeration: Dictionaries can be easily enumerated using foreach loops or LINQ queries.
  6. Type-safe: Dictionaries are type-safe, which means that you can only add or retrieve values of the specified types for the keys and values.
  7. Built-in methods: The Dictionary<TKey, TValue> class provides built-in methods for adding, removing, and accessing key-value pairs, as well as for checking if a key or value is present in the dictionary.

Interfaces Implemented by Dictionary

The Dictionary<TKey, TValue> class in C# implements several interfaces that provide additional functionality and flexibility. Here are some of the key interfaces implemented by the Dictionary class:

  1. IDictionary<TKey, TValue>: This interface provides a standard way to manipulate a dictionary that contains key-value pairs. It defines methods for adding, removing, and accessing elements based on their keys.
  2. ICollection<KeyValuePair<TKey, TValue>>: This interface provides methods for working with a collection of key-value pairs. It defines methods for adding, removing, and enumerating elements.
  3. IEnumerable<KeyValuePair<TKey, TValue>>: This interface provides the ability to iterate over a collection of key-value pairs using a foreach loop or LINQ queries.
  4. IReadOnlyDictionary<TKey, TValue>: This interface provides read-only access to a dictionary. It defines methods for accessing elements based on their keys, but not for adding or removing elements.
  5. IReadOnlyCollection<KeyValuePair<TKey, TValue>>: This interface provides read-only access to a collection of key-value pairs. It defines methods for accessing elements, but not for adding or removing elements.

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.
Frequently Used Methods in C# Dictionary

Is the Size of the C# Dictionary Fixed?

No, the size of a C# Dictionary<TKey, TValue> is not fixed. The Dictionary<TKey, TValue> class in C# automatically grows or shrinks as key-value pairs are added or removed from it.

Internally, a Dictionary<TKey, TValue> uses a hash table to store its elements, which allows for fast lookup times based on keys. The size of the hash table is not fixed and can grow or shrink as needed to accommodate the number of key-value pairs stored in the dictionary.

When a key-value pair is added to a dictionary, the dictionary checks if there is enough space in the hash table to store it. If there isn’t enough space, the dictionary automatically increases the size of the hash table to accommodate the new pair. Similarly, when a key-value pair is removed from a dictionary, the dictionary checks if the space in the hash table can be reclaimed and if so shrinks the size of the hash table accordingly.

How to Initialize Dictionary in C#?

In C#, you can initialize a Dictionary<TKey, TValue> in several ways. Here are some of the common ways to initialize a dictionary.

Using collection initializer syntax: You can use collection initializer syntax to create and initialize a dictionary in a single statement.

Dictionary<string, int> myDictionary = new Dictionary<string, int>()
{
    {"apple", 1},
    {"orange", 2},
    {"banana", 3}
};

This creates a dictionary with three key-value pairs, where the keys are strings and the values are integers.

Using Add() method: You can add key-value pairs to an empty dictionary using the Add() method.

Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary.Add("apple", 1);
myDictionary.Add("orange", 2);
myDictionary.Add("banana", 3);

This creates an empty dictionary and adds three key-value pairs to it.

Using object initializer syntax: You can use object initializer syntax to create a dictionary and then add key-value pairs to it.

Dictionary<string, int> myDictionary = new Dictionary<string, int>();
myDictionary = new Dictionary<string, int>()
{
    {"apple", 1},
    {"orange", 2},
    {"banana", 3}
};

This creates an empty dictionary and then adds three key-value pairs to it using object initializer syntax.

Using ToDictionary() method: You can create a dictionary from a collection using the ToDictionary() method.

List<string> fruits = new List<string> {"apple", "orange", "banana"};
Dictionary<string, int> myDictionary = fruits.ToDictionary(fruit => fruit, fruit => fruit.Length);

This creates a dictionary where the keys are strings from the fruits list, and the values are the length of the strings.

How to Add Items to 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 to add an 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.

How to Read 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();
        }
Mastering C# Dictionary : The Ultimate Guide for 2023 1
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();
        }

    }

Get value by key

To retrieve a value from a C# dictionary using a specific key, you can use the Dictionary<TKey, TValue> class and the TryGetValue() method. The TryGetValue() method allows you to check if a key exists in the dictionary and retrieve its corresponding value.

// Create a dictionary
Dictionary<string, int> myDictionary = new Dictionary<string, int>();

// Add key-value pairs to the dictionary
myDictionary.Add("Key1", 100);
myDictionary.Add("Key2", 200);
myDictionary.Add("Key3", 300);

// Retrieve a value using a key
if (myDictionary.TryGetValue("Key2", out int value))
{
    Console.WriteLine("The value for Key2 is: " + value);
}
else
{
    Console.WriteLine("Key2 not found in the dictionary.");
}

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 the 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#?

In C#, both Dictionary<TKey, TValue> and ConcurrentDictionary<TKey, TValue> are used to store key-value pairs. However, they have some differences in terms of their usage and behavior. Here are some key differences between the two:

  1. Thread-safety: ConcurrentDictionary<TKey, TValue> is designed to be thread-safe, which means it can be accessed and modified by multiple threads simultaneously without causing any issues. On the other hand, Dictionary<TKey, TValue> is not thread-safe, and concurrent access to it can cause issues like race conditions and data corruption.
  2. Performance: ConcurrentDictionary<TKey, TValue> is optimized for high concurrency scenarios and provides efficient thread-safe access to its elements. It uses locks to ensure that only one thread can access or modify a given key-value pair at a time. On the other hand, Dictionary<TKey, TValue> is optimized for single-threaded access and can provide better performance than ConcurrentDictionary<TKey, TValue> in scenarios where there is no need for thread safety.
  3. Memory usage: ConcurrentDictionary<TKey, TValue> uses more memory than Dictionary<TKey, TValue> because it needs to maintain additional data structures to ensure thread safety.
  4. API: ConcurrentDictionary<TKey, TValue> provides additional methods to support thread-safe access and modification of its elements. For example, it provides methods like AddOrUpdate(), GetOrAdd(), and TryAdd() that can be used to add or update elements in a thread-safe manner. Dictionary<TKey, TValue> does not provide such methods, as it is not designed for thread-safe access.

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 different-2 orders.

  • Mastering C# Dictionary : The Ultimate Guide for 2023 2
  • Mastering C# Dictionary : The Ultimate Guide for 2023 3
  • Mastering C# Dictionary : The Ultimate Guide for 2023 4

Can c# dictionary have duplicate keys?

No, in C#, a Dictionary<TKey, TValue> cannot have duplicate keys. Each key in the dictionary must be unique, and attempting to add a key that already exists will result in an ArgumentException being thrown.

When you try to add a key-value pair to a Dictionary<TKey, TValue>, the dictionary first checks if the key already exists. If it does, the value associated with the existing key is updated with the new value. If it does not exist, a new key-value pair is added to the dictionary.

Conclusion

In conclusion, a Dictionary<TKey, TValue> in C# is a collection of unique key-value pairs. It is optimized for high-performance lookups and is type-safe, meaning that you can specify the type of keys and values it will store.

It is not thread-safe by default, but you can use the ConcurrentDictionary<TKey, TValue> class to provide thread-safe access to its elements. Additionally, it does not allow duplicate keys, so if you need to store multiple values for a single key, you can use a List<T> or HashSet<T> as the value in the dictionary.

Understanding the features and differences between Dictionary<TKey, TValue> and other data structures like Hashtable and ConcurrentDictionary<TKey, TValue> can help you choose the appropriate data structure for your specific use case.

Comments are closed.

Scroll to Top