2011-07-18 51 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