Note that there are some explanatory texts on larger screens.

plurals
  1. PODistinct() with lambda?
    primarykey
    data
    text
    <p>Right, so I have an enumerable and wish to get distinct values from it.</p> <p>Using <code>System.Linq</code>, there's of course an extension method called <code>Distinct</code>. In the simple case, it can be used with no parameters, like:</p> <pre><code>var distinctValues = myStringList.Distinct(); </code></pre> <p>Well and good, but if I have an enumerable of objects for which I need to specify equality, the only available overload is:</p> <pre><code>var distinctValues = myCustomerList.Distinct(someEqualityComparer); </code></pre> <p>The equality comparer argument must be an instance of <code>IEqualityComparer&lt;T&gt;</code>. I can do this, of course, but it's somewhat verbose and, well, cludgy.</p> <p>What I would have expected is an overload that would take a lambda, say a Func&lt;T, T, bool&gt;:</p> <pre><code>var distinctValues = myCustomerList.Distinct((c1, c2) =&gt; c1.CustomerId == c2.CustomerId); </code></pre> <p>Anyone know if some such extension exists, or some equivalent workaround? Or am I missing something?</p> <p>Alternatively, is there a way of specifying an IEqualityComparer inline (embarass me)?</p> <p><strong>Update</strong></p> <p>I found a reply by Anders Hejlsberg to a <a href="http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/6834054e-e1c1-49db-970c-370a9012c675" rel="noreferrer">post</a> in an MSDN forum on this subject. He says:</p> <blockquote> <p>The problem you're going to run into is that when two objects compare equal they must have the same GetHashCode return value (or else the hash table used internally by Distinct will not function correctly). We use IEqualityComparer because it packages compatible implementations of Equals and GetHashCode into a single interface.</p> </blockquote> <p>I suppose that makes sense..</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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