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

时间:2009-07-23 02:37:46

标签: c# linq

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

使用LINQ执行此操作的最快方法是什么?

我是LINQ的新手

5 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:2)

Jason的回答是正确的,但您可以在一个LINQ操作中执行此操作。

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

        // return most frequently occurring items
        var query = from i in list
                    group i by i into g

                    let maxFreq = (from i2 in list 
                                  group i2 by i2 into g2
                                  orderby g2.Count() descending 
                                  select g2.Count()).First() 

                    let gCount = g.Count()

                    where gCount == maxFreq 

                    select  g.Key;

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

答案 2 :(得分:2)

public static Tres MostCommon<Tsrc, Tres>(this IEnumerable<Tsrc> source, Func<Tsrc, Tres> transform)
{
    return source.GroupBy(s => transform(s)).OrderByDescending(g => g.Count()).First().Key;
}

在具有整数类型的示例中,您可以将其命名为:

List<int> a = new List<int>{ 1,1,2,2,3,4,5 };
int mostCommon = a.MostCommon(x => x);

答案 3 :(得分:1)

from num in a
group num by num into numg
let c = numg.Count()
order by c descending
select new { Number = numg.Key, Count = c }

答案 4 :(得分:0)

我认为最常见的数字也可以在像这样的单一查询中实现 -

  var query = (from i in list
               group i by i into g
               orderby g.Count() descending
               select new { Key = g.Key, Count = g.Count() }).FirstOrDefault();
  if (query == null) Console.WriteLine("query = NULL");
  else  Console.WriteLine("The number '{0}' occurs {1} times.", query.Key, query.Count);

实际上并不需要空检查,但实际需要null时可能会有用(如空列表?)