ToDictionary Method

ToDictionary Method in C#

In this article, I am going to discuss the Linq ToDictionary Method in C# with some examples. Please read our previous article before proceeding to this article where we discussed the ToList and ToArray methods with some examples. Like ToList and ToArray, the ToDictionary method also belongs to the conversion operator category.

ToDictionary Method in C#:

The ToDictionary method in C# is used to creates a System.Collections.Generic.Dictionary<TKey,TValue> from an System.Collections.Generic.IEnumerable<T> according to a 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 which is basically used to extract a key from each element.
Type parameters:
  1. TSource: The type of the elements of the source sequence.
  2. TKey: The type of the key returned by keySelector.

Returns: 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: Converting List to a Dictionary.

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:

The following ToDictionary method Creates a System.Collections.Generic.Dictionary<TKey,TValue> collection from an 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 the elements of source.
  2. TKey: The type of the key returned by keySelector.
  3. TElement: The type of the value returned by the element selector.

Returns: It returns a System.Collections.Generic.Dictionary<TKey,TValue> that contains values of type TElement selected from the input sequence.

Exceptions: It throws System.ArgumentNullException when the source or key selector is null or the key selector function produces a key that is null. It also throws System.ArgumentException when the key selector produces duplicate keys for two elements.

Example:

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

Example:

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.

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();
        }
    }
}
Example:

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

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 Cast method in C# with some examples. Here, in this article, I try to explain the need and use of ToDictionary method in C# with some examples. I hope you enjoy this article.

Leave a Reply

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