LINQ's Distinct() on a particular property

后端 未结 20 2076
一向
一向 2020-11-21 05:05

I am playing with LINQ to learn about it, but I can\'t figure out how to use Distinct when I do not have a simple list (a simple list of integers is pretty easy

20条回答
  •  别跟我提以往
    2020-11-21 05:54

    What if I want to obtain a distinct list based on one or more properties?

    Simple! You want to group them and pick a winner out of the group.

    List distinctPeople = allPeople
      .GroupBy(p => p.PersonId)
      .Select(g => g.First())
      .ToList();
    

    If you want to define groups on multiple properties, here's how:

    List distinctPeople = allPeople
      .GroupBy(p => new {p.PersonId, p.FavoriteColor} )
      .Select(g => g.First())
      .ToList();
    

提交回复
热议问题