使用LINQ查找数组中最常见的数字

2 c# linq

List<int> a = new List<int>{ 1,1,2,2,3,4,5 };
Run Code Online (Sandbox Code Playgroud)

使用LINQ最快的方法是什么?

我是LINQ的新手

jas*_*son 16

这里的关键是使用Enumerable.GroupBy和聚合方法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);
}
Run Code Online (Sandbox Code Playgroud)

  • +1变量名称 (10认同)