2013-04-05 43 views
1

我在表格中有“类别”列,我想从每个类别取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) 
                 }) 
+0

我想指出你出去一** [的GroupBy(http://www.codeproject.com/Articles/35667/How -to-Use-LINQ-GroupBy)**方法。您可以按类别对数据进行分组,并从每组中取3。 – 2013-04-05 13:10:00

+0

已更新帖子 – 2013-04-05 13:16:26

+0

[LINQPad](http://www.linqpad.net/)可用于可视化像'.GroupBy'这样的运算符产生的元素。它是'.Dump()'扩展方法会显示你的结构。 – 2013-04-05 14:57:52

回答

10

你想用这样的:

var result = data.GroupBy(x => x.Category) 
       .SelectMany(x => x.Take(3)); 
+0

+1删除了我的帖子,忘记了SelectMany – Clint 2013-04-05 13:10:31

+2

@Clint:是的,这对平坦化结果很重要。 – 2013-04-05 13:11:03

+0

我收到“查询源无法识别”错误... – 2013-04-05 13:14:01