paulsm4
paulsm4

Reputation: 121649

LINQ: How do I select unique rows: max(id) with multiple columns?

This is a "toy" example of a table that has many columns and 100s of thousands of rows.

I want FILTER OUT any rows containing the same AcctNo, CustomerName and CustomerContact, but KEEP the ID for ONE of the duplicates (so I can access the record later).

Q: What's a LINQ equivalent for this SQL?

Upvotes: 1

Views: 280

Answers (2)

vendettamit
vendettamit

Reputation: 14677

You almost got it right. Just access the group properties using Key in your projection.

IQueryable<CustomerData> query =
    from c in context.CustomerData
    where c.AcctNo == acctno
    group c by new { c.AcctNo , c.CustomerName, c.CustomerContact } into gcs
    select new { newID = gcs.Max(x => x.ID), gcs.Key.AcctNo, gcs.Key.CustomerName, gcs.Key.CustomerContact }

Upvotes: 1

Anton Kovachev
Anton Kovachev

Reputation: 337

First create a custom DTO view model similar to this

public CustomerViewModel
{
   public string AcctNo { get; set; }
   public string CustomerName { get; set; }
   public string CustomerContact { get; set; }
   public int MaxId { get; set; }
}       

The query

context.CustomerData.Where(c => c.AcctNo == "1111")
       .GroupBy(c => new { c.AcctNo , c.CustomerName, c.CustomerContact })
       .Select(cg => new CustomerViewModel {
                      AcctNo  = cg.Key.AcctNo,
                      CustomerName  = cg.Key.CustomerName,
                      CustomerContact  = cg.Key.CustomerContact,
                      MaxId = cg.Max(c => c.ID)
        })

Upvotes: 1

Related Questions