Short question:
Is there a simple way in LINQ to objects to get a distinct list of objects from a list based on a key property on the objects.
Long question:
I am trying to do a Distinct() operation on a list of objects that have a key as one of their properties.
class GalleryImage { public int Key { get;set; } public string Caption { get;set; } public string Filename { get; set; } public string[] Tags {g et; set; } }
I have a list of Gallery objects that contain GalleryImage[].
Because of the way the webservice works [sic] I have duplicates of the GalleryImage object. i thought it would be a simple matter to use Distinct() to get a distinct list.
This is the LINQ query I want to use :
var allImages = Galleries.SelectMany(x => x.Images); var distinctImages = allImages.Distinct<GalleryImage>(new EqualityComparer<GalleryImage>((a, b) => a.id == b.id));
The problem is that EqualityComparer is an abstract class.
I dont want to :
- implement IEquatable on
GalleryImagebecause it is generated - have to write a separate class to implement
IEqualityCompareras shown here
Is there a concrete implementation of EqualityComparer somewhere that I’m missing?
I would have thought there would be an easy way to get ‘distinct’ objects from a set based on a key.
(There are two solutions here – see the end for the second one):
My MiscUtil library has a
ProjectionEqualityComparerclass (and two supporting classes to make use of type inference).Here’s an example of using it:
Here’s the code (comments removed)
Second solution
To do this just for Distinct, you can use the
DistinctByextension in MoreLINQ:In both cases,
ThrowIfNulllooks like this: