1

I am trying to get the distinct records

var records = (from entry in db.Table1
               select new
               {
                   RowID = entry.RowID,
                   FirstName = entry.First,
                   LastName = entry.Last,
                   Restricted = (entry.Prohibited == null || entry.Prohibited == "False") ? "Restricted" : "Not Restricted"
               }).ToList();

Here RowID is an primary key. I want to get the distinct First and Last Name.

For example:

 RowID  First  Last Prohibited ...
  1     A       B     False
  2     A       B     False
  3     A       B     False
  4     Z       Y     True
  5     Z       Y     True

What I am trying to get here is:

 RowID  First   Last  Prohibited
 1      A       B     False
 4      Z       Y     True

How can I get it?

DavidG
  • 113,891
  • 12
  • 217
  • 223
user1893874
  • 823
  • 4
  • 15
  • 38

2 Answers2

0

Simply you can do in this way:

var records = 
    (from entry in db.Table1
        select new {
            FirstName = entry.First,
            LastName = entry.Last,
            Restricted = (entry.Prohibited == null || entry.Prohibited == "False") ? "Restricted" : "Not Restricted"
        }).Distinct();

If you want the rowID also, you can read select-distinct-using-linq.

Community
  • 1
  • 1
sborfedor
  • 316
  • 1
  • 9
  • 24
0
var records = (from entry in db.Table1
               group entry by new {entry.First, entry.Last} into g
               let entry = g.FirstOrDefault()
               select new
               {
                   RowID = entry.RowID,
                   FirstName = entry.First,
                   LastName = entry.Last,
                   Restricted = (entry.Prohibited == null || entry.Prohibited == "False") ? "Restricted" : "Not Restricted"
               }).ToList();

By grouping the items by the combined first and last name, and then only taking the first item in each group, you effectively ensure that you're getting distinct items based on those values.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315