Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 605
wardh Avatar asked Jul 18 '11 09:07

wardh


People also ask

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

Is LINQ good for performance?

LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.

What is select method in LINQ?

The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.

Is LINQ select lazy?

Yes, LINQ uses lazy evaluation. The database would be queried when the foreach starts to execute, but it would fetch all the data in one go (it would be much less efficient to do millions of queries for just one result at a time).


2 Answers

var mostFollowedQuestions = context.UserIsFollowingQuestion                                     .GroupBy(q => q.QuestionId)                                     .OrderByDescending(gp => gp.Count())                                     .Take(5)                                     .Select(g => g.Key).ToList(); 
like image 146
saj Avatar answered Sep 24 '22 18:09

saj


 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); 
like image 22
Tim Lloyd Avatar answered Sep 22 '22 18:09

Tim Lloyd