查找 List<int> 中出现次数最多的数字 [英] Find the most occurring number in a List&lt;int&gt;

查看:28
本文介绍了查找 List<int> 中出现次数最多的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种使用 linq 既快捷又好用的方法?

Is there a quick and nice way using linq?

推荐答案

怎么样:

var most = list.GroupBy(i=>i).OrderByDescending(grp=>grp.Count())
      .Select(grp=>grp.Key).First();

或在查询语法中:

var most = (from i in list
            group i by i into grp
            orderby grp.Count() descending
            select grp.Key).First();

当然,如果你会重复使用这个,你可以添加一个扩展方法:

Of course, if you will use this repeatedly, you could add an extension method:

public static T MostCommon<T>(this IEnumerable<T> list)
{
    return ... // previous code
}

然后你可以使用:

var most = list.MostCommon();

这篇关于查找 List<int> 中出现次数最多的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆