如何使用 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
Ans 应该是 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();
这篇关于如何获取 Int 数组中最常见的值?(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!