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 to do, this is not the question). What I if want to use Distinct on a list of an Object on one or more properties of the object?
Example: If an object is Person
, with Property Id
. How can I get all Person and use Distinct
on them with the property Id
of the object?
Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"
How can I get just Person1 and Person3? Is that possible?
If it's not possible with LINQ, what would be the best way to have a list of Person
depending on some of its properties in .NET 3.5?
You can do it (albeit not lightning-quickly) like so:
That is, "select all people where there isn't another different person in the list with the same ID."
Mind you, in your example, that would just select person 3. I'm not sure how to tell which you want, out of the previous two.
Simple! You want to group them and pick a winner out of the group.
If you want to define groups on multiple properties, here's how:
Personally I use the following class:
Then, an extension method:
Finally, the intended usage:
The advantage I found using this approach is the re-usage of
LambdaEqualityComparer
class for other methods that accept anIEqualityComparer
. (Oh, and I leave theyield
stuff to the original LINQ implementation...)You could also use query syntax if you want it to look all LINQ-like:
Use:
The
where
helps you filter the entries (could be more complex) and thegroupby
andselect
perform the distinct function.