LINQ ToDictionary Method in C#

LINQ ToDictionary Method in C# with Examples

In this article, I am going to discuss the LINQ ToDictionary Method in C# with Examples. Please read our previous article where we discussed the LINQ ToList and ToArray Methods in C# with Examples. Like the LINQ ToList and ToArray, the ToDictionary method also belongs to the conversion operator category.

LINQ ToDictionary Method in C#:

The LINQ ToDictionary Method in C# is used to create a System.Collections.Generic.Dictionary<TKey, TValue> from the System.Collections.Generic.IEnumerable<T> according to the specified key selector. This method causes the query to be executed immediately. There are four overloaded versions available for this method. Let us start the discussion with the following overloaded version.

ToDictionary Method in C#
Parameters:

This method takes two parameters. They are as follows:

  1. source: It is the Collections.Generic.IEnumerable<T> collection from which we need to create a System.Collections.Generic.Dictionary<TKey, TValue> collection.
  2. keySelector: It is a function that is basically used to extract a key from each element.
Type Parameters:
  1. TSource: The type of elements of the source sequence.
  2. TKey: The type of the key returned by the key Selector.
Returns:
  1. It returns a System.Collections.Generic.Dictionary<TKey, TValue> collection that contains keys and values.
Exceptions:

This method throws the following two exceptions.

  1. It throws ArgumentNullException when the source or keySelector is null or the keySelector function produces a key that is null.
  2. Throws ArgumentException when the keySelector produces duplicate keys for two elements.
Example to Convert a List to a Dictionary in C#.

Here, in the following example, the product ID is the key and the Product is its value. 

using System.Linq;
using System.Collections.Generic;
using System;

namespace ConversionOperators
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }

    class Program
    {
        public static void Main()
        {
            List<Product> listProducts = new List<Product>
            {
                new Product { ID= 1001, Name = "Mobile", Price = 800 },
                new Product { ID= 1002, Name = "Laptop", Price = 900 },
                new Product { ID= 1003, Name = "Desktop", Price = 800 }
            };

            Dictionary<int, Product> productsDictionary = listProducts.ToDictionary(x => x.ID);

            foreach (KeyValuePair<int, Product> kvp in productsDictionary)
            {
                Console.WriteLine(kvp.Key + " Name : " + kvp.Value.Name + ", Price: " + kvp.Value.Price);
            }

            Console.ReadKey();
        }
    }
}

When you run the above application, it will give the output as expected as shown below.

ToDictionary Method in C# Output

Another Overloaded Version of the ToDictionary Method in C#:

The following ToDictionary method Creates a System.Collections.Generic.Dictionary<TKey, TValue> collection from the System.Collections.Generic.IEnumerable<T> according to the specified key selector and element selector.

Linq ToDictionary Method in C#
Parameters:
  1. source: It is the source System.Collections.Generic.IEnumerable<T> collection from where we need to create a System.Collections.Generic.Dictionary<TKey, TValue>.
  2. keySelector: A function to extract a key from each element.
  3. elementSelector: A transform function to produce a result element value from each element.
Type Parameters:
  1. TSource: The type of elements of source.
  2. TKey: The type of the key returned by the key Selector.
  3. TElement: The type of value returned by the element selector.
Returns:
  1. It returns a System.Collections.Generic.Dictionary<TKey, TValue> that contains values of type TElement selected from the input sequence.
Exceptions:
  1. It throws System.ArgumentNullException when the source or key selector is null or the key selector function produces a key that is null.
  2. It also throws System.ArgumentException when the key selector produces duplicate keys for two elements.
Example to Understand the above LINQ ToDictionary Method in C#:

In the following example, we are converting List<Product> to a Dictionary. Here, the product ID is the key and the Product name is its value.

using System.Linq;
using System.Collections.Generic;
using System;

namespace ConversionOperators
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }

    class Program
    {
        public static void Main()
        {
            List<Product> listProducts = new List<Product>
            {
                new Product { ID= 1001, Name = "Mobile", Price = 800 },
                new Product { ID= 1002, Name = "Laptop", Price = 900 },
                new Product { ID= 1003, Name = "Desktop", Price = 800 }
            };

            Dictionary<int, string> productsDictionary = listProducts.ToDictionary(x => x.ID, x => x.Name);

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

            Console.ReadKey();
        }
    }
}
Output:

Linq ToDictionary Method in C# Output

What happens when the key is the same for two elements?

In the following example, it throws a System.ArgumentException as there are two products with the same ID (i.e. Products with id 1001) and we are using ID as the key for the dictionary.

using System;
using System.Collections.Generic;
using System.Linq;
namespace ConversionOperators
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }

    class Program
    {
        public static void Main()
        {
            List<Product> listProducts = new List<Product>
            {
                new Product { ID= 1001, Name = "Mobile", Price = 800 },
                new Product { ID= 1001, Name = "Laptop", Price = 900 },
                new Product { ID= 1003, Name = "Desktop", Price = 800 }
            };

            Dictionary<int, string> productsDictionary = listProducts.ToDictionary(x => x.ID, x => x.Name);

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

            Console.ReadKey();
        }
    }
}
What happens when the source is null?

In the following example, it will throw System.ArgumentNullException as the source (i.e listProducts) is null.

using System; 
using System.Collections.Generic; 
using System.Linq;
namespace ConversionOperators
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
    }

    class Program
    {
        public static void Main()
        {
            List<Product> listProducts = null;

            Dictionary<int, string> productsDictionary = listProducts.ToDictionary(x => x.ID, x => x.Name);

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

            Console.ReadKey();
        }
    }
}

In the next article, I am going to discuss the need and use of the LINQ Cast Method in C# with Examples. Here, in this article, I try to explain the need and use of the LINQ ToDictionary Method in C# with Examples. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *