我如何使用Linq呢?

时间:2011-03-09 23:27:42

标签: c# linq

想象一下,我有以下数组:

int[] player = new int[5] { 1, 2, 3, 4, 4 };
int[] computer = new int[5] { 1, 1, 1, 3, 5 };

如何使用Linq查询获取每个集合中每个数字的次数?

3 个答案:

答案 0 :(得分:3)

这将为您提供player数组中每个数字的频率,同样适用于computer数组:

var playerFrequencies = player.GroupBy(n => n)
                              .Select(g => new { Number = g.Key, 
                                                Frequency = g.Count() })
                              .ToList();

答案 1 :(得分:3)

var count =
    from i in player
    group i by i into g
    select new { Number = g.Key, Count = g.Count() }

答案 2 :(得分:0)

  int HowManyTimes(IEnumerable<int> numberCollection, int numberToFind){
        return numberCollection.Count(x = >x == numberToFind);
  }