Alexey Titov
Alexey Titov

Reputation: 84

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();

Upvotes: 1

Views: 1391

Answers (2)

krillgar
krillgar

Reputation: 12805

You want to get the distinct Operators 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();

Upvotes: 2

Saket Bihari
Saket Bihari

Reputation: 11

Just use .Distinct() before .To list().

Upvotes: 0

Related Questions