简体   繁体   中英

Not getting Distinct Items when using Linq to List?

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.

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?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM