Distinct by property of class with LINQ

user278618 picture user278618 · Mar 29, 2010 · Viewed 157.2k times · Source

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?

Answer

Guffa picture Guffa · Mar 29, 2010

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();