What is the purpose of "ToLookup" operator in LINQ?
The purpose of the ToLookup
operator in LINQ is to create a lookup table from a sequence (collection) of elements. It allows you to group the elements based on a key and retrieve the associated values.
The ToLookup
operator is similar to the GroupBy
operator in LINQ, but it differs in its return type. While GroupBy
returns an IEnumerable<IGrouping<TKey, TElement>>
, ToLookup
returns an ILookup<TKey, TElement>
.
Here's the syntax of the ToLookup
operator in LINQ:
ILookup<TKey, TElement> lookup = sequence.ToLookup(keySelector, elementSelector);
-
sequence
represents the collection or sequence of elements from which you want to create the lookup table.
-
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:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Define a class for Person
class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
// Create an array of Person objects
Person[] people = new Person[]
{
new Person { Id = 1, Name = "Alice", City = "New York" },
new Person { Id = 2, Name = "Bob", City = "London" },
new Person { Id = 3, Name = "Charlie", City = "New York" }
};
// Create a lookup using ToLookup
ILookup<string, Person> cityLookup = people.ToLookup(person => person.City);
// Display the people in each city
foreach (var cityGroup in cityLookup)
{
Console.WriteLine($"City: {cityGroup.Key}");
foreach (var person in cityGroup)
{
Console.WriteLine($" Name: {person.Name}");
}
}
}
}
Output:
City: New York
Name: Alice
Name: Charlie
City: London
Name: Bob
In this program, we define a Person
class with properties for Id
, Name
, and City
. We create an array of Person
objects called people. We then use LINQ's ToLookup
method to create a lookup that groups people by their City
.
The ILookup
interface represents a collection of keys each mapped to one or more values. In this case, we use the City
as the key, and the values are the people who live in that city. We iterate through the lookup to display the names of people in each city.
The ToLookup
operator is useful when you want to group elements based on a key and retrieve the associated values as a lookup table. It provides a convenient way to organize and access the data in a grouped manner using keys and values.