Note that there are some explanatory texts on larger screens.

plurals
  1. POCan you create a simple 'EqualityComparer<T>' using a lambda expression
    text
    copied!<p>IMPORTANT: THIS IS <strong>NOT A LINQ-TO-SQL</strong> QUESTION. This is LINQ to objects.</p> <p><strong>Short question:</strong> </p> <p>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.</p> <p><strong>Long question:</strong></p> <p>I am trying to do a <a href="http://www.hookedonlinq.com/DistinctOperator.ashx" rel="noreferrer"><code>Distinct()</code></a> operation on a list of <strong>objects</strong> that have a key as one of their properties.</p> <pre><code>class GalleryImage { public int Key { get;set; } public string Caption { get;set; } public string Filename { get; set; } public string[] Tags {g et; set; } } </code></pre> <p>I have a list of <code>Gallery</code> objects that contain <code>GalleryImage[]</code>.</p> <p>Because of the way the webservice works [sic] I have duplicates of the <code>GalleryImage</code> object. i thought it would be a simple matter to use <code>Distinct()</code> to get a distinct list.</p> <p>This is the LINQ query I want to use :</p> <pre><code>var allImages = Galleries.SelectMany(x =&gt; x.Images); var distinctImages = allImages.Distinct&lt;GalleryImage&gt;(new EqualityComparer&lt;GalleryImage&gt;((a, b) =&gt; a.id == b.id)); </code></pre> <p>The problem is that <code>EqualityComparer</code> is an abstract class.</p> <p>I dont want to :</p> <ul> <li>implement IEquatable on <code>GalleryImage</code> because it is generated</li> <li>have to write a separate class to implement <code>IEqualityComparer</code> as <a href="http://www.hookedonlinq.com/DistinctOperator.ashx" rel="noreferrer">shown here</a></li> </ul> <p>Is there a concrete implementation of <code>EqualityComparer</code> somewhere that I'm missing?</p> <p>I would have thought there would be an easy way to get 'distinct' objects from a set based on a key.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload