In this article, let’s describe how to use the LINQ ToDictionary() method in C#. We will start by defining this method and how it works. Then, we will proceed to show several ways of invoking it.

Ultimately, we will discuss different situations where we can utilize the LINQ ToDictionary() method to transform data in our applications.

To download the source code for this article, you can visit our GitHub repository.

Alright, let’s dive in.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

What Does the ToDictionary() Method Do?

In C#, the ToDictionary() method is a LINQ extension method that we can invoke on any collection that implements the IEnumerable<T> interface to convert it to a Dictionary<TKey, TValue> instance. When we invoke this method on an enumerable, we can pass in an argument to select the keys we want in our dictionary from the enumerable. Alternatively, we can pass in two arguments to select both the keys and their associated values.

It’s also important to mention that the ToDictionary() method is an immediate execution method. This means that whenever we call this method as part of a LINQ query, it immediately executes the query, retrieves the resulting enumerable, and creates our dictionary instance.

Alright! With these details in mind, let’s now use the ToDictionary() method to convert an enumerable to a dictionary.

Create the Sample Data

Our input enumerable will be a list of countries. Therefore, let’s first define a Country record:

public record Country(string Name, string Capital, string Continent);

Here, we define a record that specifies that all its instances must have a name, a capital, and a continent.

With that, let’s now create the list of countries:

private static readonly List<Country> _countries
    = [
        new("Egypt", "Cairo", "Africa"),
        new("India", "New Delhi", "Asia"),
        new("Chile", "Santiago", "South America"),
        new("Australia", "Canberra", "Oceania")
      ];

Here, we create a list of four countries. For each one, we define its name, capital, and continent.

Different Overloads of the ToDictionary() Method

With our input list ready, let’s explore some overloads of the ToDictionary() method.

Creating a Dictionary by Specifying Keys Only

First, let’s examine an overload of the ToDictionary() method that allows us to create a dictionary by specifying only the keys we want in it:

public static Dictionary<string, Country> CallToDictionaryWithKeysOnly()
    => _countries.ToDictionary(c => c.Name);

Here, we use to ToDictionary<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) overload to create a dictionary.

This overload allows us to pass in just one Func<TSource, TKey> argument to select the keys we want in our dictionary. This function is called a key selector, and in this case, we use it to specify that the keys in our dictionary should be the names of all the countries in our list.

When we call this method, it returns a dictionary that maps the names of countries in our list to their corresponding Country objects.

Before we proceed to the next overload, we should note the ToDictionary() method doesn’t always run smoothly. Invalid inputs can cause two kinds of exceptions to be raised. Firstly, if our input enumerable is null, or our key selector generates a null key, this method will raise an ArgumentNullException. Secondly, if our key selector function returns a key that already exists in our dictionary, the ToDictionary() method will raise an ArgumentException.

Therefore, if there is any chance that our input collection might be null or that our key selector might return a null key or duplicate key, it is advisable to add guard clauses to handle these cases. With these clauses, we ensure that our application does not behave strangely or waste computing resources on unnecessary processes.

Creating a Dictionary By Specifying Both Keys and Values

Moving on, let’s explore another overload of the ToDictionary() method that we can use to create a dictionary by specifying both the keys we desire and their associated values:

public static Dictionary<string, string> CallToDictionaryWithKeysAndValues()
    => _countries.ToDictionary(c => c.Name, c => c.Capital);

With the ToDictionary<TSource,TKey,TElement>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TSource,TElement>) overload, we can specify the keys we want in our resulting dictionary, as well as their values.

Here, we specify that we want a Dictionary<string, string> that has our countries’ names as keys and their capitals as values.

Great! With that, we’ve successfully discussed two important overloads of the ToDictionary() method. As we’ve seen, these overloads are pretty useful tools for creating dictionaries from enumerables in our applications.

To explore other less-widely used overloads of the ToDictionary() method, kindly visit the Enumerable.ToDictionary Method documentation.

As a next step, let’s consider different scenarios where the ToDictionary() method will be of great use to us in our applications.

When Should We Use the ToDictionary() Method in C#?

Firstly, whenever we have an enumerable such as a list, an array, a stack, or any other collection type that implements the IEnumerable<T> interface and we wish to convert it to a dictionary, we should utilize the ToDictionary() method.

Additionally, the ToDictionary() method proves useful in situations where we want to group elements from our enumerables based on certain properties. For example, when we used the first overload, specifying only the key selector function, we were simply grouping the countries in our list by their names.

Finally, this method can come in handy when we aim to create key-value pairs from the results of our LINQ queries.

Conclusion

In this article, we’ve examined the LINQ ToDictionary method. We explored what it is, what it does, how to use it, and when to use it.

With this information, we now have a solid understanding of an important method for transforming enumerables into dictionaries in our applications.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!