| by Arround The Web | No comments

C# ToDictionary Method

The ToDictionary function in C# is a LINQ extension function that enables you to transform a data collection into a dictionary which offers a clear and practical way to map the entities to distinct keys and related values. It requires two arguments, two delegates or lambda expressions, one for choosing the key and an additional one for choosing the value for every object in the collection. In this article, we will utilize some C# code examples to demonstrate the uses of the ToDictionary function.

Syntax:

Let’s break down and understand each component that is provided within the following syntax of the C# ToDictionary function one by one:

var dict = collection.ToDictionary(keySelector, elementSelector);
  • The “var” keyword is cast off here to define the type category of the resultant “dict” dictionary. In most cases, it is Dictionary<K, V> where K is the type of the key and V is the type category of the dictionary value.
  • The “collection” element represents the source collection that you want to convert into a “dict” dictionary. It can be any class that implements the IEnumerable<T> interface such as a list, array, or query result.
  • The “keySelector” keyword is a delegate or lambda expression that specifies how to extract the key from each item in the collection. It gets an element from the collection as an argument and gives back the key value for that item. The key should be unique for each item in the collection, as dictionaries cannot have duplicate keys.
  • The “elementSelector” keyword refers to a delegate or lambda expression that specifies how to extract the value from each item in the collection. It also gets an element of the collection as an argument and yields the value for that item.

After executing the ToDictionary function, you will have a new dictionary object where each item from the collection is represented as a key-value pair.

Example 1:

Let’s have a fresh start on this guide by demonstrating the use of the ToDictionary function in C# with the help of a code example. Let’s go through it step by step.

The code begins with the required namespaces being imported: System, System.Collections.Generic, and System.Linq. These namespaces provide the necessary classes and extension methods to work with collections and LINQ. The “Dummy” class is defined which contains the “Main” method of this C# program.

Inside the “Main” method, a list named “L” is created. This list holds three string elements that represent the names of different perfumes of the user’s choice. The ToDictionary method is called on the “L” list. It converts the list into a dictionary. Each string element in the list serves as both the key and the value in the resulting dictionary.

The dictionary is created with a case-insensitive key comparison using the StringComparer.OrdinalIgnoreCase parameter which is primarily used to specify a case-insensitive comparison when checking for the existence of keys. An “if” statement checks if the dictionary contains the “bombshell” key while ignoring its case. If the key is found, the code snippet within the “if” section will be processed. Inside the “if” block, the Console.WriteLine(“Bombshell exists”) statement is executed which prints the “Bombshell exists” message to the console.

using System;

using System.Collections.Generic;

using System.Linq;

class Dummy

{

  static void Main()

  {

    List<string> L = new List<string>() { "BlackOpium", "Bombshell", "GucciFlora" };

    var Perfume = L.ToDictionary(x => x, x => true, StringComparer.OrdinalIgnoreCase);

    if (Perfume.ContainsKey("bombshell"))

    {

        Console.WriteLine("Bombshell exists");

    }

  }

}

Since the dictionary is created with a case-insensitive comparison, the “bombshell” key matches the actual “Bombshell” key in the dictionary. As a result, the “Bombshell exists” message is printed on the console as displayed in the following attached output image:

Example 2:

Within the previous code example, we demonstrated how a simple collection can be converted into a dictionary via the ToDictionary function. Now, we will move towards a little advanced code example of C# for the demonstration of the C# ToDictionary function uses. Let’s break down the code line by line.

This illustration code snippet starts by bringing in the same compulsory namespaces: System, System.Collections.Generic, and System.Linq. These namespaces provide the required classes and extension methods to work with collections and LINQ for this code example. The “Dummy” class is defined which is an entry point.

Inside the “Main” method of C# language, a list named “L” is formed. This list contains three objects of the “Data” class which represents the different cosmetic products with their prices and brands. Each data object is initialized using the object initializer syntax. The “Price” and “Brand” properties of each object are set with specific values.

Here comes the ToDictionary method. It is called here on the “L” list. It converts the list into a dictionary where the “Price” property is used as the key and the “Brand” property is used as the value. The resulting dictionary is assigned to the “Dic” variable as mentioned in the following provided code snippet. A ”foreach” loop is cast-off to call over the key-value pairs in the “Dic” dictionary.

Inside the loop, the key and value of each pair are accessed using the “Key” and “Value” properties of the KeyValuePair<Key, Value> structure. The Console.WriteLine function statement prints each key-value pair to the console. The output is formatted using the string interpolation to display the price and brand information separately.

Here, the “Data” class is defined with two properties: “Price” (an integer that represents the price of a cosmetic product) and “Brand” (a string that represents the brand name of a product).

using System;

using System.Collections.Generic;

using System.Linq;

class Dummy

{

  static void Main()

  {

    List<Data> L = new List<Data>()

    {

      new Data { Price = 13000, Brand = "Huda Beauty" },

      new Data { Price = 15000, Brand = "Charlotte Telburry" },

      new Data { Price = 11000, Brand = "Nars" }

    };

    Dictionary<int, string> Dic = L.ToDictionary(p => p.Price, p => p.Brand);

    foreach (var v in Dic)

    {

        Console.WriteLine($"Price: {v.Key}, Brand: {v.Value}");

    }

  }

}

class Data

{

    public int Price { get; set; }

    public string Brand { get; set; }

}

When the code is executed, it creates a list of data objects, converts the list into a dictionary using the ToDictionary method, and then displays the key-value pairs of the dictionary using the “foreach” loop.

The output for this code example is provided in the following. It shows the prices and brands of cosmetic products that are stored in the dictionary based on specific properties, providing a convenient way to organize and access the data in key-value pairs. The output of the previous code shows three records for the dictionary:

Conclusion

This C# guide demonstrated the use of the C# ToDictionary method via some basic and precise code illustrations. By offering a clear and expressive mechanism to describe the key-value pairs, the ToDictionary method makes it easier to turn a collection into a dictionary. It is a strong C# utility to manipulate and transform the data.

Share Button

Source: linuxhint.com

Leave a Reply