Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Distinct Select [duplicate]

Tags:

c#

lambda

linq

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?

like image 941
Rudolph Opperman Avatar asked Oct 26 '25 03:10

Rudolph Opperman


1 Answers

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());
like image 100
Selman Genç Avatar answered Oct 28 '25 17:10

Selman Genç



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!