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?
If you don't want to add the MoreLinq library to your project just to get the
DistinctBy
functionality then you can get the same end result using the overload of Linq'sDistinct
method that takes in anIEqualityComparer
argument.You begin by creating a generic custom equality comparer class that uses lambda syntax to perform custom comparison of two instances of a generic class:
Then in your main code you use it like so:
Voila! :)
The above assumes the following:
Person.Id
is of typeint
people
collection does not contain any null elementsIf the collection could contain nulls then simply rewrite the lambdas to check for null, e.g.:
EDIT
This approach is similar to the one in Vladimir Nesterovsky's answer but simpler.
It is also similar to the one in Joel's answer but allows for complex comparison logic involving multiple properties.
However, if your objects can only ever differ by
Id
then another user gave the correct answer that all you need to do is override the default implementations ofGetHashCode()
andEquals()
in yourPerson
class and then just use the out-of-the-boxDistinct()
method of Linq to filter out any duplicates.