1

When using the query operator Distinct() the types in the queried sequence must either provide suitable overloads of GetHashCode() and Equals() or you have to pass an implementation of IEqualityComparer<T>.

My question: Why is there no overload of Distinct() accepting a Delegate instance (e.g. Comparison<T>)? - If it was existent a more lighweight lambda expression could be passed (more lightweight than an implementation of IEqualityComparer<T>). - Am I missing something here?

Nico
  • 1,554
  • 1
  • 23
  • 35
  • Distinct will check both Equals and GetHashCode if it must... how lightweight of a lambda do you think you'll actually be able to provide? – Didaxis Nov 17 '11 at 19:34
  • 1
    possible duplicate of [Distinct() with lambda?](http://stackoverflow.com/questions/1300088/distinct-with-lambda) – Magnus Nov 17 '11 at 19:35
  • Hi ErOx! I suggested a solution like Tor Haugen proposed in Distinct() with lambda?: var distinctValues = myCustomerList.Distinct((c1, c2) => c1.CustomerId == c2.CustomerId); Hi Magnus! Hm I didn't find Tor's question, so mine is a duplicate, yes! Thanks for your comments! – Nico Nov 17 '11 at 19:45
  • But that only works if the only thing you want to consider is a single property... which is not typically what someone will want. If that is what you want, however, then I would say Jon Skeet's answer and implementation is the way to go (i.e., DistinctBy(x => x.PropertyName) – Didaxis Nov 17 '11 at 19:59
  • Yes, I know Jon's DistinctBy(), maybe the real question is, why this is not existent as standard query operator (paraphrasing SLaks' answer). But often you want to compare a single item (I think, this _is_ a typical case.). – Nico Nov 17 '11 at 20:04

2 Answers2

4

Because it uses GetHashCode().
You cannot make a delegate that gives hash codes.

It could take two delegates, but that would be confusing.

It would be better to ask why there isn't a DistinctBy() method that takes a projection.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

otherwise you can try MoreLINQ and its method DistincBy

pierroz
  • 7,653
  • 9
  • 48
  • 60