c# - 获取列表中出现次数最多的前 3 个数字

标签 c# list linq

假设我有一个整数列表。 我添加了一些值:

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/

相关文章:

c# - 为什么我的 LINQ 插入在 SQL Server CE 3.5 中不持久?

c# - 在运行时创建 LINQ 查询到 EntityFramework 中的 GroupBy(具有继承)

c# - 获取ListView项的子项相对于Form的坐标

c# - 重用模型属性作为 SelectList 项的来源会导致在一个选择控件中选择了不正确的选项

c# - Starcounter - 更改属性的数据类型

java - 返回数组列表对象 java 中的列表

c# - 使用 Visual Studio 创建 T-SQL 表单

python - 最多 4 个列表的维恩图 - 输出交集和唯一集

python - 对数字列表进行排名,允许并列

c# - 将 Func<T, bool> 传递给 LINQ Where