Search code examples
c#linqlinq-to-dataset

LINQ query for getting row with max date in grouped table


I have following datatable structure

ID    Date            Vendor  Grade
 1    20-nov-2013     xyz      A
 2    26-Apr-2013     abc      B
 1    21-nov-2013     pqr      D
 1    10-nov-2013     abc      C
 2    15-dec-2013     pqr      A
 2    20-May-2013     abc      B

What i want group this table on column ID and then select the row that has maximum dateTime value

Sample Answer would be for this table is

ID    Date            Vendor  Grade
 1    21-nov-2013     pqr      D
 2    15-dec-2013     pqr      A

I have tried following so far but struck with no clue what to do next

var chk = (from s in dt.AsEnumerable()
          where s.Field<int>("ID") == 1 || s.Field<int>("ID") == 2            
          select s).GroupBy(k => k.Field<int>("ID")});

Solution

  • Group your rows by ID, then sort each group of rows by Date and select first one row:

    var chk = from r in dt.AsEnumerable()
              let id = r.Field<int>("ID")
              where id == 1 || id == 2
              group r by id into g
              select g.OrderByDescending(r => r.Field<DateTime>("Date")).First();
    

    Produces

    ID    Date            Vendor  Grade
     1    21-nov-2013     pqr      D
     2    15-dec-2013     pqr      A