I have a collection:
List<Car> cars=new List<Car>
Cars are uniquely identified by 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?
I have a collection:
List<Car> cars=new List<Car>
Cars are uniquely identified by 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?
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();
You can implement an IEqualityComparer and use that in your Distinct extension.
class CarEqualityComparer : IEqualityComparer<Car>
{
#region IEqualityComparer<Car> Members
public bool Equals(Car x, Car y)
{
return x.CarCode.Equals(y.CarCode);
}
public int GetHashCode(Car obj)
{
return obj.CarCode.GetHashCode();
}
#endregion
}
And then
var uniqueCars = cars.Distinct(new CarEqualityComparer());