简体   繁体   中英

LINQ - how to create a list of distinct items

How can I make a LINQ query that would return a new list of distinct Operators from the Workpacks table (DB is not normalized). I got this query, but I don't know how to use DISTINCT properly, so that SQL server doesn't return duplicate values

Instance.CriteriaOperatorList = 
    (from v in context.Workpacks
     select new FilterCriteriaItem()
     {
         GUID = Guid.NewGuid(),
         Name = v.Operator,
     }).ToList();

You want to get the distinct Operator s from the Workpack , then get those. The easiest way to do that is to not use the SQL LINQ syntax.

Instance.CriteriaOperatorList = context.Workpacks
                                       // Only request the Operator names
                                       .Select(w => w.Operator)
                                       // But just request the distinct names
                                       .Distinct()
                                       // Then select into your DTO.
                                       .Select(o => new FilterCriteriaItem
                                       {
                                           GUID = Guid.NewGuid(),
                                           Name = o // o is the Operator from Workpack
                                       })
                                       .ToList();

只需在.To list()之前使用.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