Home >Backend Development >C++ >How to Group Person Objects by ID and Retrieve Associated Car Names in LINQ?
Efficiently Grouping Person Objects and Retrieving Car Names with LINQ
This example demonstrates how to group a collection of Person
objects by their PersonId
and retrieve the associated car names using LINQ's GroupBy
or ToLookup
methods. Assume you have a list of Person
objects, each with a PersonId
and a car
property. The goal is to group persons with the same PersonId
and obtain a list of cars for each group.
The GroupBy
method provides a concise way to achieve this grouping:
<code class="language-csharp">var results = persons.GroupBy(p => p.PersonId) .Select(g => new { PersonId = g.Key, Cars = g.Select(p => p.car).ToList() });</code>
This code first groups the persons
list by the PersonId
property. Then, for each group (g
), it creates an anonymous object containing the PersonId
( g.Key
) and a list of car names (g.Select(p => p.car).ToList()
).
Alternatively, the ToLookup
method creates a lookup structure, similar to a dictionary, offering efficient key-based access:
<code class="language-csharp">var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);</code>
Accessing the cars for a specific personId
is then very simple:
<code class="language-csharp">var carsForPerson = carsByPersonId[personId].ToList(); // Convert to List if needed</code>
Both approaches effectively group the data, allowing for easy retrieval and manipulation of car names associated with each PersonId
. Choose the method that best suits your needs and coding style; ToLookup
might be preferable if you anticipate frequent lookups by PersonId
.
The above is the detailed content of How to Group Person Objects by ID and Retrieve Associated Car Names in LINQ?. For more information, please follow other related articles on the PHP Chinese website!