在linq中选择,分组和最大查询

时间:2012-07-24 07:59:39

标签: c# linq datatable

我真的不了解linq,你能帮我解决一下这个问题吗?

 SELECT   *
  FROM   attachment
 WHERE   create_date IN (  SELECT   MAX (create_date)
                             FROM   attachment
                         GROUP BY   document_id, attachment_type)

如何将其更改为linq语句。我正在使用DataTable。

抱歉,我的DataTable包含字段attachment_id,document_id,attachment_type和create_date。我真的不能使用dt.Select():(

我还需要将其更改回DataTable或Datarow

1 个答案:

答案 0 :(得分:1)

虽然你的问题不是很清楚,但我认为这就是你要找的东西:

var orderedDocGroups = tbl.AsEnumerable()
.GroupBy(r => new
{
    DocID = r.Field<int>("document_id"),
    AttID = r.Field<int>("attachment_type"),
})
.Select(group => new{
    DocID = group.Key.DocID,
    AttID = group.Key.AttID,
    MaxCreationDateRow = group
        .OrderByDescending(r => r.Field<DateTime>("create_date"))
        .First()
}).OrderByDescending(x => x.MaxCreationDateRow.Field<DateTime>("create_date"));

foreach(var docGroup in orderedDocGroups)
{
    var docInfo = string.Join(", ", string.Format("document_id:{0} attachment_type:{1} create_date:{2}",
                    docGroup.DocID, docGroup.AttID, docGroup.MaxCreationDateRow.Field<DateTime>("create_date")));
    Console.WriteLine(docInfo);
}
  

如何将其更改回datarow?

// convert back to a DataTable only with the rows with max creationdate per group:
DataTable tblMaxCreationDate = orderedDocGroups
    .Select(g => g.MaxCreationDateRow)
    .CopyToDataTable();

以下是测试上述内容的示例代码:

var tbl = new DataTable();
tbl.Columns.Add("attachment_id",typeof(Int32));
tbl.Columns.Add("document_id",typeof(Int32));
tbl.Columns.Add("attachment_type",typeof(Int32));
tbl.Columns.Add("create_date",typeof(DateTime));

var rnd = new Random();
for(int i=0; i < 10; i++)
{
    tbl.Rows.Add(i, rnd.Next(1, 5), rnd.Next(1, 3), new DateTime(2012, 07, 24, rnd.Next(1, 24), 0, 0));
}