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?
You can use grouping, and get the first car from each group:
Use MoreLINQ, which has a
DistinctBy
method :)(This is only for LINQ to Objects, mind you.)
You can check out my PowerfulExtensions library. Currently it's in a very young stage, but already you can use methods like Distinct, Union, Intersect, Except on any number of properties;
This is how you use it:
Same approach as Guffa but as an extension method:
Used as:
Another way to accomplish the same thing...
It's possible to create an extension method to do this in a more generic way. It would be interesting if someone could evalute performance of this 'DistinctBy' against the GroupBy approach.
You can't effectively use
Distinct
on a collection of objects (without additional work). I will explain why.The documentation says:
For objects that means it uses the default equation method to compare objects (source). That is on their hash code. And since your objects don't implement the
GetHashCode()
andEquals
methods, it will check on the reference of the object, which are not distinct.