2011-07-18 55 views
12

我想選擇我的表中最常見的五個值,並將它們返回到列表中。使用LINQ選擇最常見的值使用LINQ

var mostFollowedQuestions = (from q in context.UserIsFollowingQuestion 
           select *top five occuring values from q.QuestionId*).toList(); 

任何想法?

感謝

回答

29
 var mostFollowedQuestions = context.UserIsFollowingQuestion 
            .GroupBy(q => q.QuestionId) 
            .OrderByDescending(gp => gp.Count()) 
            .Take(5) 
            .Select(g => g.Key).ToList(); 
+1

謝謝。偉大的作品 – wardh

+1

@wardh我想你會發現這實際上給你的*最少*頻繁發生的價值觀。我的答案略有不同,但按要求最頻繁發生。 –

+0

被編輯爲給予最頻繁 - Orderby by order bydescending – saj

22
int[] nums = new[] { 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7 }; 

IEnumerable<int> top5 = nums 
      .GroupBy(i => i) 
      .OrderByDescending(g => g.Count()) 
      .Take(5) 
      .Select(g => g.Key); 
+0

感謝。奇蹟般有效! – wardh