Reputation: 9737
Here is how I am attempting to get a distinct List of items...
var queryResults = PatientList.Distinct();
PatientList = queryResults.ToList<SelectListItem>();
For some reason, I am not getting a distinct list here.
Upvotes: 3
Views: 9162
Reputation: 7483
Use
var queryResults = PatientList.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault())
PatientList = queryResults.ToList<SelectListItem>();
You can always try
PatientList = PatientList.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault()).ToList<SelectListItem>();
It will give you the distinct results based off whatever you group by
Check out http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx
Also another question for reference: Returning a Distinct IQueryable with LINQ?
Upvotes: 9
Reputation: 671
Not sure what kind of items your PatientList contains, but I guess you have to implement IEquatable on your custom object.
This have been aswered before here: Distinct not working with LINQ to Objects
Upvotes: 1
Reputation: 292345
Your SelectListItem
class needs to override Equals
and GetHashCode
(and optionally implement IEquatable<SelectListItem>
). Otherwise, different instances with the same values will be considered different.
Another option is to implement a IEqualityComparer<SelectListItem>
and pass it as the second parameter to Distinct
.
Upvotes: 1