简体   繁体   中英

Linq take 3 records from each category

I have column "Category" in my table and I want to take 3 rows from each category. here example of my table:

 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

And this is why I want to get back:

 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

How I can done it with LINQ?

I tried to do like this:

.GroupBy(x => x.Category).Take(3)

But after that I cant use .Select

Update: When I using SelectMany I'm getting an error:

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])}

Update 2: Here is my code:

.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)
                                                         })

You want to use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM