查找列表&LT最发生数; INT> [英] Find the most occurring number in a List<int>

查看:206
本文介绍了查找列表&LT最发生数; 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
}

然后你可以使用:

Then you can use:

var most = list.MostCommon();

这篇关于查找列表&LT最发生数; INT&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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