-2

我不太了解 linq,你能帮我解决这个问题吗?

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

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

抱歉,我的 DataTable 具有字段 attachment_id、document_id、attachment_type 和 create_date。而且我真的不能使用 dt.Select() :(

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

4

1 回答 1

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

如何将其更改回数据行?

// 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));
}
于 2012-07-24T08:17:07.383 回答