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")});
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
Query syntax:
var chk = from r in dt.AsEnumerable() /*where 1=1 */
group r by r.Field<int>("ID") into g
select g.OrderByDescending(t => t.Field<int>("ID")).First();
Fluent syntax :
dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.OrderByDescending(t => t.Field<int>("ID")).First());
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.