IMPORTANT : THIS IS NOT A LINQ-TO-SQL QUESTION. This is LINQ to objects.
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
GalleryImage
because it is generated - have to write a separate class to implement
IEqualityComparer
as 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.