简体   繁体   中英

ASP.net Core C# Linq Distinct not working

I've trying to use Linq for the first time to get distinct values from a list in ASP.net Core Razor Pages.

For this i'm using the below code but it just returns all the rows from the original list including the duplicates:

PLDistinct = PL.Select(p => new ProcessListSummary {  Title=  p.Title, 
                                                  WSID = p.WSID,
                                                  QImageTnURL = p.QImageTnURL,
                                                  QImageURL = p.QImageURL,
                                                  QDescription = p.QDescription,
                                                  PComplete= p.PComplete,
                                                  MIdent = p.MIdent,
                                                  WID = p.WID})
                                                  .Distinct().ToList();

What am I doing wrong please?

Many thanks

Your class ProcessListSummary probably does not override Equals and GetHashCode , so the default will be used from System.Object that just compares references. You use always a new instance of ProcessListSummary , so all are considered to be unequal.

So either override Equals + GetHashCode meaningfully, by comparing the relevant properties, and/or implement IEquatable<ProcessListSummary> (in the same way) or pass a custom IEqualityComparer<ProcessListSummary> to Distinct . The latter should be done if you have multiple ways to compare this class or you don't want to change (or can't change) it in general.

Another option is to use Distinct on an anonymous type or tuple which provide that feature:

PLDistinct = PL
    .Select(p => (p.Title,p.WSID,p.QImageTnURL,p.QImageURL,p.QDescription,p.PComplete,p.MIdent,p.WID))
    .Distinct()
    .Select(p => new ProcessListSummary {  Title=  p.Title, 
                                           WSID = p.WSID,
                                           QImageTnURL = p.QImageTnURL,
                                           QImageURL = p.QImageURL,
                                           QDescription = p.QDescription,
                                           PComplete= p.PComplete,
                                           MIdent = p.MIdent,
                                           WID = p.WID})
    .ToList();

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