[英]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.