简体   繁体   English

LINQ查询以获取分组表中具有最大日期的行

[英]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 我想要将此表分组为列ID ,然后选择具有最大dateTime值的行

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: ID对行进行分组,然后按Date对每组行进行排序,然后选择第一行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM