我想使用Linq来选择和分组DataTable行......我想按照每组中“Max”创建日期的降序排序......是否有任何可以对此进行的改进代码,特别是我可以创建Linq的OrderByDescending部分,例如使用:
orderby {... something here...} descending
---当前代码---
DataTable dt = ReadDataTable();
var rows = (from row in dt.AsEnumerable()
where row.Field<bool>("Active") == true
group row by new
{
CollectionId = row.Field<int>("CollectionId"),
CollectionName = row.Field<string>("CollectionName"),
} into grp
select new
{
CollectionId = grp.Key.CollectionId,
CollectionName = grp.Key.CollectionName,
MaxCreated = grp.Max(r => r.Field<DateTime>("Created"))
}).OrderByDescending(r => r.MaxCreated);
答案 0 :(得分:2)
您可以使用let
clause在复杂的LINQ查询中保存中间结果,以便在后续排序和选择中使用。在您的情况下,您可以使用它来存储最终结果以供后续排序。
即。你可以在没有OrderByDescending()
lambda的情况下重写你的Linq,如下所示:
DataTable dt = ReadDataTable();
var rows = from row in dt.AsEnumerable()
where row.Field<bool>("Active")
group row by new
{
CollectionId = row.Field<int>("CollectionId"),
CollectionName = row.Field<string>("CollectionName"),
} into grp
let result = new
{
CollectionId = grp.Key.CollectionId,
CollectionName = grp.Key.CollectionName,
MaxCreated = grp.Max(r => r.Field<DateTime>("Created")),
}
orderby result.MaxCreated descending
select result;