2013-12-10 30 views
3

我有一個集合。我需要通過「A」屬性對集合進行分組。我必須按「B」屬性對每個組進行排序。然後從每個組中選擇前5個。組的集合,並採取第一5從每個組

任何人都可以提出這個LINQ查詢?

我嘗試的辦法是行不通的。

(from item in Recipes 
orderby item.Rating descending 
group item by item.MainCategory).Take(5) 

查詢應返回IEnumerable<IGrouping<string, myrecipetype>>

+0

你需要'GroupBy','OrderBy'和'Take'運營商 –

+0

的OP已經展示了他的企圖試試這個,我不明白這個問題是什麼? –

+0

@DeeMac看它什麼時候被修改了,留下時代評論... – gleng

回答

5

您正在首五個組別。相反,你需要選擇從每個組第一五項:

from item in Recipes 
orderby item.Rating descending  
group item by item.MainCategory into g 
select g.Take(5) 

UPDATE:

from item in Recipes 
orderby item.Rating descending  
group item by item.MainCategory into g 
select g.Take(5).GroupBy(item => item.MainCategory).First() 
+0

這將不返回組。 – Jawahar

+0

@XAMLLover是的,這將返回'IEnumerable '而不是組 –

+0

請看看我更新的問題。 – Jawahar

1

編輯:在你的情況,有加分選(業務方案進行了更新後):

Recipes.GroupBy(recipy => recipy.MainCategory) 
     .Select(recipyGroup => recipyGroup.OrderBy(recipy => recipy.Rating) 
             .Take(5)) 
相關問題