Linq从每个类别中取3条记录
本文关键字:3条 记录 Linq | 更新日期: 2023-09-27 18:07:52
我有列"类别"在我的表,我想从每个类别采取3行。下面是我的表的例子:
ID | Category | Text
----------------------
01 | TST | Text here
02 | TST | Text2 here
03 | TST | Text3 here
04 | TST | Text4 here
01 | TST02 | Text here
02 | TST02 | Text2 here
03 | TST02 | Text3 here
04 | TST02 | Text4 here
05 | TST02 | Text5 here
这就是我想回去的原因:
ID | Category | Text
----------------------
01 | TST | Text here
02 | TST | Text2 here
03 | TST | Text3 here
01 | TST02 | Text here
02 | TST02 | Text2 here
03 | TST02 | Text3 here
我如何用LINQ完成它?
我试着这样做:
.GroupBy(x => x.Category).Take(3)
但是之后我不能使用。select
更新:当我使用SelectMany时,我得到一个错误:
更新2:Query Source could not be identified: ItemName = x, ItemType = System.Linq.IGrouping ' 2[System.String, add . models .], Expression = from IGrouping ' 2 x in {from Notification w in value(NHibernate.Linq.NhQueryable ' 1[add . models .Notification]) where ([w]. add . models .Notification]。UserId == 04bccode -46d0-44f8-814b-346d5510acb8) order [w]。Time asc select [w] => GroupBy([w])。类别,[w])}
下面是我的代码:
.GroupBy(x => x.Category).SelectMany(x => x.Take(3)).Select(
s =>
new NotificationData
{
Category = s.Category,
Text = s.Text,
Time = DateTime.Now.Subtract(s.Time)
})
你想用这个:
var result = data.GroupBy(x => x.Category)
.SelectMany(x => x.Take(3));