Linq - Group By Id, Order By 然后 select 每个分组的前 5 个
Linq - Group By Id, Order By and Then select top 5 of each grouping
在 linq 中有什么方法可以按 Id 分组,按降序排列然后 select 每个分组的前 5 名?现在我有一些代码如下所示,但我使用了 .Take(5)
并且显然 select 是前 5 名,无论分组如何。
Items = list.GroupBy(x => x.Id)
.Select(x => x.OrderByDescending(y => y.Value))
.Select(y => new Home.SubModels.Item {
Name= y.FirstOrDefault().Name,
Value = y.FirstOrDefault().Value,
Id = y.FirstOrDefault().Id
})
你快到了。在 Select
语句中使用 Take
:
var items = list.GroupBy(x => x.Id)
//For each IGrouping - order nested items and take 5 of them
.Select(x => x.OrderByDescending(y => y.Value).Take(5))
这将 return 和 IEnumerable<IEnumerable<T>>
。如果你想让它变平,用 SelectMany
替换 Select
在 linq 中有什么方法可以按 Id 分组,按降序排列然后 select 每个分组的前 5 名?现在我有一些代码如下所示,但我使用了 .Take(5)
并且显然 select 是前 5 名,无论分组如何。
Items = list.GroupBy(x => x.Id)
.Select(x => x.OrderByDescending(y => y.Value))
.Select(y => new Home.SubModels.Item {
Name= y.FirstOrDefault().Name,
Value = y.FirstOrDefault().Value,
Id = y.FirstOrDefault().Id
})
你快到了。在 Select
语句中使用 Take
:
var items = list.GroupBy(x => x.Id)
//For each IGrouping - order nested items and take 5 of them
.Select(x => x.OrderByDescending(y => y.Value).Take(5))
这将 return 和 IEnumerable<IEnumerable<T>>
。如果你想让它变平,用 SelectMany
Select