小编典典

查找列表中出现次数最多的数字

c#

有没有使用linq的快捷好方法?


阅读 593

收藏
2020-05-19

共1个答案

小编典典

怎么样:

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();

当然,如果您将反复使用它,则可以添加扩展方法:

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

然后,您可以使用:

var most = list.MostCommon();
2020-05-19