尽管您的问题不是很清楚,但我认为这就是您要查找的内容:
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));
}