我在表格中有“类别”列,我想从每个类别取3行。 这里我表的例子:Linq从每个类别取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)
但在那之后我不能使用。选择
更新: 当我使用的SelectMany我得到一个错误:
Query Source could not be identified: ItemName = x, ItemType = System.Linq.IGrouping`2[System.String,ADDE.Models.Notification], Expression = from IGrouping`2 x in {from Notification w in value(NHibernate.Linq.NhQueryable`1[ADDE.Models.Notification]) where ([w].UserId == 04bccede-46d0-44f8-814b-346d5510acb8) orderby [w].Time asc select [w] => GroupBy([w].Category, [w])}
更新2: 这是我的鳕鱼E:
.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)
})
我想指出你出去一** [的GroupBy(http://www.codeproject.com/Articles/35667/How -to-Use-LINQ-GroupBy)**方法。您可以按类别对数据进行分组,并从每组中取3。 – 2013-04-05 13:10:00
已更新帖子 – 2013-04-05 13:16:26
[LINQPad](http://www.linqpad.net/)可用于可视化像'.GroupBy'这样的运算符产生的元素。它是'.Dump()'扩展方法会显示你的结构。 – 2013-04-05 14:57:52