Alex Rivera | Logout

Select most frequent value using LINQ

Asked 2011-07-18T09:33:05.450
32

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

Edit
Report

1 Answer

36
 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);
answered 2011-07-18T09:37:23.477

Your Answer