wardh
wardh

Reputation: 479

Select most frequent value using LINQ

I'm trying to select the top five most frequent values in my table and return them in a List.

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

Any idea?

Thanks

Upvotes: 32

Views: 21902

Answers (2)

saj
saj

Reputation: 4796

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

Upvotes: 58

Tim Lloyd
Tim Lloyd

Reputation: 38464

 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);

Upvotes: 36

Related Questions