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; } }
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" } };
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);
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)}"); }
Alternatively, ToLookup
creates a dictionary-like structure (ILookup<int, string>
):
var carsByPersonID = persons.ToLookup(p => p.PersonID, p => p.Car);
Accessing data is then simpler:
List<string> carsForPerson1 = carsByPersonID[1].ToList(); Console.WriteLine($"Cars for Person 1: {string.Join(", ", carsForPerson1)}");
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!