假设我有一个整数列表。 我添加了一些值:
list.Add(5);
list.Add(5);
list.Add(27);
list.Add(3);
list.Add(4);
list.Add(4);
list.Add(29);
list.Add(3);
如何获取3个最出现的号码?像这样:5、3 和 4。
我已经尝试过:
public static IEnumerable<T> Mode<T>(this IEnumerable<T> input)
{
var dict = input.ToLookup(x => x);
if (dict.Count == 0)
return Enumerable.Empty<T>();
var maxCount = dict.Max(x => x.Count());
return dict.Where(x => x.Count() == maxCount).Select(x => x.Key);
}
但它只返回给我一个数字。
最佳答案
这应该可以正常工作
var topThreeMostOccuring = arr.GroupBy(x => x)
.OrderByDescending(g => g.Count())
.SelectMany(x => x.Take(1)).Take(3);
关于c# - 获取列表中出现次数最多的前 3 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59707532/