Linq从每个类别中获取3条记录

Zil*_*ael 1 c# linq

我的表中有"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
Run Code Online (Sandbox Code Playgroud)

这就是我想回来的原因:

 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
Run Code Online (Sandbox Code Playgroud)

我如何用LINQ完成它?

我试着这样做:

.GroupBy(x => x.Category).Take(3)
Run Code Online (Sandbox Code Playgroud)

但在那之后我无法使用.选择

更新: 当我使用SelectMany时,我收到一个错误:

查询源无法确定:ITEMNAME = X,的ItemType = System.Linq.IGrouping`2 [System.String,ADDE.Models.Notification],表达来自=在IGrouping`2 {X从通知w的值(NHibernate.Linq .NhQueryable`1 [ADDE.Models.Notification]),其中([W] .UserId == 04bccede-46d0-44f8-814b-346d5510acb8)的OrderBy [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)
                                                         })
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 10

你想用这个:

var result = data.GroupBy(x => x.Category)
                 .SelectMany(x => x.Take(3));
Run Code Online (Sandbox Code Playgroud)

  • @Clint:是的,平衡结果很重要. (2认同)