4

I have this lambda and would like it to return Distinct list.

var ResourceTypeNameList = Resources.Select(r => new bl_SelectBox{ text=r.ResourceTypeName, value=r.resourceTypeID }).Distinct();

Am I missing something or should that return a distinct list?

Servy
  • 202,030
  • 26
  • 332
  • 449
Rudolph Opperman
  • 197
  • 1
  • 1
  • 15
  • It should but according to equality comparison for bl_SelectBox (if it's a custom reference type without anything else than its properties...each reference isn't equal to anything else). – Adriano Repetti Jan 27 '15 at 15:18
  • @AdrianoRepetti The current resources list has text = "Car", value = 1 X 2. However it returns them twice and It should return only once. – Rudolph Opperman Jan 27 '15 at 15:20
  • Is there something that you want to be distinct from each object? like text or value? In your case, it will return distinct references. – Ramie Jan 27 '15 at 15:21
  • Does `bl_SelectBox` override `GetHashCode` and `Equals`? If not, try to implement this, or give an additional parameter to `Distinct` implementing `IEqualityComparer` – Caramiriel Jan 27 '15 at 15:24
  • Complementing Caramiriel's comment - if not, `Distinct` might not filter anything as the input is a sequence of distinct objects. – Codor Jan 27 '15 at 15:25
  • 1
    It must distinct on value=r.resourceTypeID but i need to select text=r.ResourceTypeName. – Rudolph Opperman Jan 27 '15 at 15:25
  • @RudolphOpperman itself Distinct() doesn't know how to detect equality. That's why your object has to override GetHashCode and Equals or you specify a custom IEualityComparer as parameter. – Adriano Repetti Jan 27 '15 at 16:10

1 Answers1

14

If you don't override Equals and GetHashCode in your class or provide a custom equality comparer Distinct method uses default equality comparer for the type.And it compares reference types by references. Not by the property values. If you don't want this behaviour either override the relevant methods in your class or if you can't change the class implement an IEqualityComparer for the type and pass it to Distinct:

var ResourceTypeNameList = Resources
   .Select(r => new bl_SelectBox{ text=r.ResourceTypeName, value=r.resourceTypeID })
   .Distinct(new MyEqualityComparer());

Another quick solution would be using GroupBy:

var ResourceTypeNameList = Resources
  .Select(r => new bl_SelectBox{ text=r.ResourceTypeName, value=r.resourceTypeID })
  .GroupBy(x => x.SomeProperty)
  .Select(x => x.First());
Selman Genç
  • 100,147
  • 13
  • 119
  • 184