Find the most occurring number in a List

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

Leave a Comment

tech