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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With