Home > Backend Development > C++ > How Can I Group Person Objects by PersonID and Get Unique Car Models Using LINQ?

How Can I Group Person Objects by PersonID and Get Unique Car Models Using LINQ?

Mary-Kate Olsen
Release: 2025-02-02 00:16:12
Original
988 people have browsed it

How Can I Group Person Objects by PersonID and Get Unique Car Models Using LINQ?

Use linq to group Personid

In this example, your goal is to group the Person object list according to the Personid attribute and retrieve the only car model list for everyone. To this end, you can use the Groupby extension provided by Linq.

The following linq query demonstrates how to group the Personid and extract the car list associated with everyone:

var results = from p in persons
              group p.car by p.PersonId into g
              select new { PersonId = g.Key, Cars = g.Distinct().ToList() };
Copy after login
<明> Explanation:

<作> Create all CAR attributes based on each unique Personid value.
  • The result of the grouping is the sequence of anonymous objects. Each object represents a group and contains Personid as the key and car list as the CARS attribute. group p.car by p.PersonId Methods ensure that only the only car model is returned.
  • Distinct() or, you can use lookup to effectively retrieve the car list of specific Personid:

<法> Usage:

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

If there is no designated person ID in this method, a empty sequence is returned. Make sure to return the only car model list.

The above is the detailed content of How Can I Group Person Objects by PersonID and Get Unique Car Models Using 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