| by Arround The Web | No comments

Convert the C# LINQ to Dictionary

In C# LINQ, creating a dictionary from System.Collections.Generic.IEnumerable<T> is possible using the ToDictionary() method. This method creates a dictionary with <TKey,TValue> from the given <IEnumerable<T>. The System.ArgumentNullException is thrown if the data source, keySelector, or elementSelector is null. Also, if the keySelector produces duplicate keys for two elements, the System.ArgumentException is thrown. In this guide, we will discuss how to create a dictionary from the list data source by overloading two methods.

Syntax:

1. If you want to create a dictionary according to specified key selector and element selector functions from the given data source, overload the following method:

Parameters:

    1. source: Source can be an IEnumerable (list) in which the dictionary is created from this source.
    2. keySelector: This is a function which is used to get the key from each element.
    3. elementSelector: This is a function which is used to get the element.
    4. TSource: This is the type parameter that specifies the type of the data source.
    5. TKey: This is the type parameter that specifies the type of the key.
    6. TElement: This is the type parameter that specifies the type of element.

2. If you want to create a dictionary according to the specified key selector function from the given data source, overload the following method:

Parameters:

    1. source: Source can be an IEnumerable (list) in which the dictionary is created from this source.
    2. keySelector: This is a function which is used to get the key from each element.
    3. TSource: This refers to the type of the data source.
    4. TKey: It specifies the type of key.

Example 1: Specified Key Selector and Element Selector Function

Create a list with the “Account” type that holds four attributes (Acc_ID, Acc_Name, Industry, Revenue) with five records.

1. Create a dictionary from the previous list with the key as Acc_ID and Value as Acc_Name.
2. Create a dictionary from the previous list with the key as Acc_Name and Value as Revenue.

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

    class AccountInformation
    {
        public static void Main()
        {
            // Create List of type - Account.
            List details = new List();
            // Add 5 records to the List.
            details.Add( new Account{Acc_ID= 1, Acc_Name = "Linux", Industry = "Education",Revenue=2500});
            details.Add( new Account{Acc_ID= 2, Acc_Name = "Python", Industry = "Bootcamp",Revenue=10000});
            details.Add( new Account{Acc_ID= 3, Acc_Name = "Java", Industry = "Education",Revenue=500});
            details.Add( new Account{Acc_ID= 4, Acc_Name = ".NET", Industry = "Training",Revenue=2080});
            details.Add( new Account{Acc_ID= 5, Acc_Name = "Oracle", Industry = "Job",Revenue=2090});
           
            // Create a Dictionary from the above List with Key as Acc_ID and Value as Acc_Name
            Console.WriteLine(" ----Key as Acc_ID and Value as Acc_Name----");
            Dictionary accounts_dict1 = details.ToDictionary(j => j.Acc_ID, j=> j.Acc_Name);

            foreach (KeyValuePair i in accounts_dict1)
            {
                Console.WriteLine("Account-Id :" + i.Key + " Account-Name :" + i.Value);
            }
           
            // Create a Dictionary from the above List with Key as Acc_Name and Value as Revenue
            Console.WriteLine(" ----Key as Acc_Name and Value as Revenue----");
            Dictionary accounts_dict2 = details.ToDictionary(l => l.Acc_Name, l=> l.Revenue);

            foreach (KeyValuePair k in accounts_dict2)
            {
                Console.WriteLine("Account-Name :" + k.Key + " Account-Revenue :" + k.Value);
            }
           
        }
}

// Create class named - Account with four attributes
   public class Account
    {
        public int Acc_ID { get; set; }
        public string Acc_Name { get; set; }
        public string Industry { get; set; }
        public int Revenue { get; set; }
    }

Output:

Explanation: 

1. Create a class named “Account” with four attributes.

2. In the main class, create list of “Account” type and insert five records into it.

3. Create a dictionary from the previous list with the key as Acc_ID and Value as Acc_Name. Here, we specify the TKey as int and the TElement as string. Inside the ToDictionary() method, we pass the Acc_ID in the keySelector and the Acc_Name in the elementSelector.  Finally, we use the “foreach” loop to iterate the dictionary and return the keys and values using the key and value properties.

4. Create a dictionary from the previous list with the key as Acc_Name and the value as Revenue. Here, we specify the TKey as string and the TElement as int. Inside the ToDictionary() method, we pass the Acc_Name in the keySelector and the Revenue in the elementSelector. Finally, we use the “foreach” loop to iterate the dictionary and return the keys and values using the key and value properties.

Example 2: Specified Key Selector

Use the previous code and create a dictionary from the previous list with the key as Acc_ID.

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

    class AccountInformation
    {
        public static void Main()
        {
            // Create List of type - Account.
            List details = new List();
            // Add 5 records to the List.
            details.Add( new Account{Acc_ID= 1, Acc_Name = "Linux", Industry = "Education",Revenue=2500});
            details.Add( new Account{Acc_ID= 2, Acc_Name = "Python", Industry = "Bootcamp",Revenue=10000});
            details.Add( new Account{Acc_ID= 3, Acc_Name = "Java", Industry = "Education",Revenue=500});
            details.Add( new Account{Acc_ID= 4, Acc_Name = ".NET", Industry = "Training",Revenue=2080});
            details.Add( new Account{Acc_ID= 5, Acc_Name = "Oracle", Industry = "Job",Revenue=2090});
           
            // Create a Dictionary from the above List with Key as Acc_ID.
            Dictionary accounts_dict = details.ToDictionary(j => j.Acc_ID);
            foreach (KeyValuePair i in accounts_dict)
            {
                Console.WriteLine("Key:" + i.Key + "-->  Account-Name :" + i.Value.Acc_Name
                + " Account-Industry :" + i.Value.Industry
                + " Account-Revenue :" + i.Value.Revenue);
            }
           
        }
}

// Create class named - Account with four attributes
   public class Account
    {
        public int Acc_ID { get; set; }
        public string Acc_Name { get; set; }
        public string Industry { get; set; }
        public int Revenue { get; set; }
    }

Output:

Explanation:

Here, we create a dictionary with the key as Acc_ID. This acts as the key for each record in the dictionary that we created from the list. After that, we use the “foreach” loop to get the keys and values (with attributes) using the key and value properties.

Example 3: Duplicate Keys – ArgumentException

Create a list with two records and try to convert it into a dictionary with the Acc_ID as key.

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

    class AccountInformation
    {
        public static void Main()
        {
            // Create List of type - Account.
            List details = new List();
            // Add 2 records to the List.
            details.Add( new Account{Acc_ID= 1, Acc_Name = "Linux", Industry = "Education",Revenue=2500});
            details.Add( new Account{Acc_ID= 1, Acc_Name = "Python", Industry = "Bootcamp",Revenue=10000});
           
            // Try to create a Dictionary from the above List with Key as Acc_ID.
            Dictionary accounts_dict = details.ToDictionary(j => j.Acc_ID);
           
        }
}

// Create class named - Account with four attributes
   public class Account
    {
        public int Acc_ID { get; set; }
        public string Acc_Name { get; set; }
        public string Industry { get; set; }
        public int Revenue { get; set; }
    }

Exception:

An unhandled exception which is System.ArgumentException is raised since the key is duplicate (1) in both the Acc_ID’s.

Example 4: Null Source – ArgumentNullException

Create a list with the “Account” type and assign null to it. Try to create a dictionary from the previous list with the key as Acc_ID.

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

    class AccountInformation
    {
        public static void Main()
        {
            // Create List of type - Account and assign null to it.
            List details = null;
           
            // Try to create a Dictionary from the above List with Key as Acc_ID.
            Dictionary accounts_dict = details.ToDictionary(j => j.Acc_ID);
           
        }
}

// Create class named - Account with four attributes
   public class Account
    {
        public int Acc_ID { get; set; }
        public string Acc_Name { get; set; }
        public string Industry { get; set; }
        public int Revenue { get; set; }
    }

Exception:

An unhandled exception which is System.ArgumentNullException is raised since the list is null.

Conclusion

We learned how to create a dictionary from the IEnumerable (here, it is list) using the ToDictionary() method in C# LINQ. This method can be overloaded in two ways. We discussed both methods with examples. Also, we learned the two exception cases that are raised by this method when the data source/ keySelector/ elementSelector is null and the keys are duplicate.

Share Button

Source: linuxhint.com

Leave a Reply