C# 使用LINQ选择最频繁的值

C# 使用LINQ选择最频繁的值,c#,sql,linq,entity-framework,C#,Sql,Linq,Entity Framework,我正在尝试选择表中最常见的五个值,并在列表中返回它们 var mostFollowedQuestions = (from q in context.UserIsFollowingQuestion select *top five occuring values from q.QuestionId*).toList(); 有什么想法吗 谢谢int[]nums=new[]{1,1,1,2,2,3,3,4,4,5,5,6,6,

我正在尝试选择表中最常见的五个值,并在列表中返回它们

    var mostFollowedQuestions = (from q in context.UserIsFollowingQuestion
                                 select *top five occuring values from q.QuestionId*).toList();
有什么想法吗

谢谢

int[]nums=new[]{1,1,1,2,2,3,3,4,4,5,5,6,6,7};
IEnumerable top5=nums
.GroupBy(i=>i)
.OrderByDescending(g=>g.Count())
.采取(5)
.选择(g=>g.Key);

@wardh我想你会发现这实际上给了你最不频繁出现的值。我的答案略有不同,但根据要求给出了最频繁出现的答案。编辑后的结果给出了Orderby到OrderbyDescending的最频繁更改
 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);
var mostFollowedQuestions = context.UserIsFollowingQuestion
                                    .GroupBy(q => q.QuestionId)
                                    .OrderByDescending(gp => gp.Count())
                                    .Take(5)
                                    .Select(g => g.Key).ToList();