Home >Backend Development >C++ >How Can I Group Data by a Specific Key Using LINQ's GroupBy and ToLookup Methods?

How Can I Group Data by a Specific Key Using LINQ's GroupBy and ToLookup Methods?

Linda Hamilton
Linda HamiltonOriginal
2025-02-02 00:11:09961browse

How Can I Group Data by a Specific Key Using LINQ's GroupBy and ToLookup Methods?

LINQ: Grouping Data by Key with GroupBy and ToLookup

LINQ provides efficient methods for grouping data based on specific criteria. This is particularly useful when dealing with collections of objects and needing to aggregate information based on a common key.

Let's illustrate with a Person class:

<code class="language-csharp">class Person
{
    public int PersonID { get; set; }
    public string Car { get; set; }
}</code>

Consider a list of Person objects, where some individuals may have multiple entries (e.g., owning multiple cars):

<code class="language-csharp">List<Person> persons = new List<Person>()
{
    new Person { PersonID = 1, Car = "Ferrari" },
    new Person { PersonID = 1, Car = "BMW" },
    new Person { PersonID = 2, Car = "Audi" }
};</code>

To group these persons by PersonID and list their cars, we use LINQ's GroupBy method:

<code class="language-csharp">var results = persons.GroupBy(p => p.PersonID, p => p.Car);</code>

results is an IEnumerable<IGrouping<int, string>>. Each IGrouping represents a group with a common PersonID (accessible via result.Key), and contains a sequence of car strings (result). To access this data:

<code class="language-csharp">foreach (var result in results)
{
    int personID = result.Key;
    List<string> cars = result.ToList(); // Convert to List for easier access
    Console.WriteLine($"Person ID: {personID}, Cars: {string.Join(", ", cars)}");
}</code>

Alternatively, ToLookup creates a dictionary-like structure (ILookup<int, string>):

<code class="language-csharp">var carsByPersonID = persons.ToLookup(p => p.PersonID, p => p.Car);</code>

Accessing data is then simpler:

<code class="language-csharp">List<string> carsForPerson1 = carsByPersonID[1].ToList();
Console.WriteLine($"Cars for Person 1: {string.Join(", ", carsForPerson1)}");</code>

Both GroupBy and ToLookup offer efficient ways to group data based on a key, making data manipulation in LINQ more streamlined. ToLookup provides direct dictionary-like access, while GroupBy offers more flexibility for complex grouping scenarios.

The above is the detailed content of How Can I Group Data by a Specific Key Using LINQ's GroupBy and ToLookup Methods?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn