在使用LINQ数组找到最频繁的号码 [英] Find the most frequent numbers in an array using LINQ

查看:104
本文介绍了在使用LINQ数组找到最频繁的号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<int> a = new List<int>{ 1,1,2,2,3,4,5 };



什么是与LINQ做到这一点?

What's the quickest way to do this with LINQ?

我是新来的LINQ

推荐答案

这里的关键是使用的 Enumerable.GroupBy 和聚合方法的 Enumerable.Count

The key here is using Enumerable.GroupBy and the aggregation method Enumerable.Count:

List<int> list = new List<int>() { 1,1,2,2,3,4,5 };

// group by value and count frequency
var query = from i in list
            group i by i into g
            select new {g.Key, Count = g.Count()};

// compute the maximum frequency
int whatsTheFrequencyKenneth = query.Max(g => g.Count);

// find the values with that frequency
IEnumerable<int> modes = query
                              .Where(g => g.Count == whatsTheFrequencyKenneth)
                              .Select(g => g.Key);

// dump to console
foreach(var mode in modes) {
    Console.WriteLine(mode);
}

这篇关于在使用LINQ数组找到最频繁的号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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