Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct by property of class with LINQ [duplicate]

Tags:

c#

linq

distinct

I have a collection:

List<Car> cars = new List<Car>(); 

Cars are uniquely identified by their property CarCode.

I have three cars in the collection, and two with identical CarCodes.

How can I use LINQ to convert this collection to Cars with unique CarCodes?

like image 229
user278618 Avatar asked Mar 29 '10 12:03

user278618


1 Answers

You can use grouping, and get the first car from each group:

List<Car> distinct =   cars   .GroupBy(car => car.CarCode)   .Select(g => g.First())   .ToList(); 
like image 63
Guffa Avatar answered Oct 27 '22 01:10

Guffa