[英]Linq take 3 records from each category
我的表中有“类别”列,我想从每个类别中提取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时出现错误:
无法识别查询来源:ItemName = x,ItemType = System.Linq.IGrouping`2 [System.String,ADDE.Models.Notification],Expression =来自IGrouping`2 x in {from通知w in value(NHibernate.Linq .NhQueryable`1 [ADDE.Models.Notification]),其中[[w] .UserId == 04bccede-46d0-44f8-814b-346d5510acb8)排序为[w]。时间递增选择[w] => GroupBy([w]。类别[[w])}
更新2:这是我的代码:
.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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.