我如何使用linq查找数据集中最常出现的数据?

时间:2009-04-03 03:16:36

标签: c# linq

List<int> a = 11,2,3,11,3,22,9,2

//output
11

3 个答案:

答案 0 :(得分:4)

这可能不是最有效的方法,但它可以完成工作。

public static int MostFrequent(IEnumerable<int> enumerable)
{
    var query = from it in enumerable
                 group it by it into g
                 select new {Key = g.Key, Count = g.Count()} ;
   return query.OrderByDescending(x => x.Count).First().Key;
} 

有趣的单行版本......

public static int MostFrequent(IEnumerable<int> enumerable)
{
    return (from it in enumerable
                 group it by it into g
                 select new {Key = g.Key, Count = g.Count()}).OrderByDescending(x => x.Count).First().Key;

}

答案 1 :(得分:2)

a.GroupBy(item => item).
  Select(group => new { Key = group.Key, Count = group.Count() }).
  OrderByDescending(pair => pair.Count).
  First().
  Key;

答案 2 :(得分:0)

另一个例子:

IEnumerable<int> numbers = new[] { 11, 2, 3, 11, 3, 22, 9, 2 };
int most = numbers
    .Select(x => new { Number = x, Count = numbers.Count(y => y == x) })
    .OrderByDescending(z => z.Count)
    .First().Number;