我如何使用 Linq 来实现此目的?

发布于 2024-10-21 03:50:01 字数 174 浏览 2 评论 0原文

假设我有以下数组:

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

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

Imagine I have the following arrays:

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

How can I use a Linq query to fetch the amount of times each number is in each collection?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一梦等七年七年为一梦 2024-10-28 03:50:01
var count =
    from i in player
    group i by i into g
    select new { Number = g.Key, Count = g.Count() }
var count =
    from i in player
    group i by i into g
    select new { Number = g.Key, Count = g.Count() }
情未る 2024-10-28 03:50:01

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

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

This would give you the frequency of each number in the player array, same would work for the computer array:

var playerFrequencies = player.GroupBy(n => n)
                              .Select(g => new { Number = g.Key, 
                                                Frequency = g.Count() })
                              .ToList();
妞丶爷亲个 2024-10-28 03:50:01
  int HowManyTimes(IEnumerable<int> numberCollection, int numberToFind){
        return numberCollection.Count(x = >x == numberToFind);
  }
  int HowManyTimes(IEnumerable<int> numberCollection, int numberToFind){
        return numberCollection.Count(x = >x == numberToFind);
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文