Find the most occurring number in a List<int>

Solution 1:

How about:

var most = list.GroupBy(i=>i).OrderByDescending(grp=>grp.Count())
      .Select(grp=>grp.Key).First();

or in query syntax:

var most = (from i in list
            group i by i into grp
            orderby grp.Count() descending
            select grp.Key).First();

Of course, if you will use this repeatedly, you could add an extension method:

public static T MostCommon<T>(this IEnumerable<T> list)
{
    return ... // previous code
}

Then you can use:

var most = list.MostCommon();

Solution 2:

Not sure about the lambda expressions, but I would

  1. Sort the list [O(n log n)]

  2. Scan the list [O(n)] finding the longest run-length.

  3. Scan it again [O(n)] reporting each number having that run-length.

This is because there could be more than one most-occurring number.