如何获得 Int 数组中最常见的值?(C#)

问题描述:

如何使用 C# 获取 Int 数组中最常见的值

How to get the most common value in an Int array using C#

例如:数组具有以下值:1, 1, 1, 2

eg: Array has the following values: 1, 1, 1, 2

答案应该是 1

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 版本:

Lambda version on the second:

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