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
Release: 2025-02-02 00:11:09
Original
960 people have browsed it

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:

class Person
{
    public int PersonID { get; set; }
    public string Car { get; set; }
}
Copy after login

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

List<Person> persons = new List<Person>()
{
    new Person { PersonID = 1, Car = "Ferrari" },
    new Person { PersonID = 1, Car = "BMW" },
    new Person { PersonID = 2, Car = "Audi" }
};
Copy after login

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

var results = persons.GroupBy(p => p.PersonID, p => p.Car);
Copy after login

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:

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)}");
}
Copy after login

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

var carsByPersonID = persons.ToLookup(p => p.PersonID, p => p.Car);
Copy after login

Accessing data is then simpler:

List<string> carsForPerson1 = carsByPersonID[1].ToList();
Console.WriteLine($"Cars for Person 1: {string.Join(", ", carsForPerson1)}");
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template