What is the purpose of "ToDictionary" method in LINQ?
The purpose of the ToDictionary method in LINQ is to create a dictionary from a sequence (collection) of elements. It allows you to transform the sequence into a dictionary, where each element is associated with a key-value pair.
Here's the syntax of the ToDictionary method in LINQ:
Dictionary dictionary = sequence.ToDictionary(keySelector, elementSelector);
-
sequence represents the collection or sequence of elements from which you want to create the dictionary.
-
keySelector is a lambda expression or delegate that specifies the key for each element in the sequence.
-
elementSelector is a lambda expression or delegate that specifies the value for each element in the sequence.
Example:
var people = new[]
{
new Person { Id = 11, Name = "Alice" },
new Person { Id = 12, Name = "Davis Bob" },
new Person { Id = 13, Name = "Charlie" }
};
Dictionary<int, string> dictionary = people.ToDictionary(person => person.Id, person => person.Name);
In this example, the ToDictionary method is used to create a dictionary where the Id property of each Person object is used as the key, and the Name property is used as the value. The resulting dictionary maps the IDs to the corresponding names.
The ToDictionary method is useful when you have a sequence of elements and you want to transform it into a dictionary for efficient key-based access. It provides a convenient way to create dictionaries from sequences using key and value selectors.