Ant*_*ram 28
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();
Run Code Online (Sandbox Code Playgroud)
只需要价值而不是数量,你就可以做到
var query = (from item in array
group item by item into g
orderby g.Count() descending
select g.Key).First();
Run Code Online (Sandbox Code Playgroud)
第二个Lambda版本:
var query = array.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
Run Code Online (Sandbox Code Playgroud)
Guf*_*ffa 15
一些老式的高效循环:
var cnt = new Dictionary<int, int>();
foreach (int value in theArray) {
if (cnt.ContainsKey(value)) {
cnt[value]++;
} else {
cnt.Add(value, 1);
}
}
int mostCommonValue = 0;
int highestCount = 0;
foreach (KeyValuePair<int, int> pair in cnt) {
if (pair.Value > highestCount) {
mostCommonValue = pair.Key;
highestCount = pair.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
现在mostCommonValue包含最常见的值,并highestCount包含它发生的次数.