How to get the most common value in an Int array? (C#)

var query = (from item in array
        group item by item into g
        orderby g.Count() descending
        select new { Item = g.Key, Count = g.Count() }).First();

For just the value and not the count, you can do

var query = (from item in array
                group item by item into g
                orderby g.Count() descending
                select g.Key).First();

Lambda version on the second:

var query = array.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();

Leave a Comment