Home > Backend Development > C++ > How to Group Person Objects by ID and Retrieve Associated Car Names in LINQ?

How to Group Person Objects by ID and Retrieve Associated Car Names in LINQ?

Linda Hamilton
Release: 2025-02-02 00:06:10
Original
321 people have browsed it

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:

1

2

var results = persons.GroupBy(p => p.PersonId)

                     .Select(g => new { PersonId = g.Key, Cars = g.Select(p => p.car).ToList() });

Copy after login

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:

1

var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);

Copy after login

Accessing the cars for a specific personId is then very simple:

1

var carsForPerson = carsByPersonId[personId].ToList(); // Convert to List if needed

Copy after login

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!

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