【问题标题】:Count elements in array of arrays equal to specified value计算数组数组中等于指定值的元素
【发布时间】:2017-11-18 03:32:57
【问题描述】:

我有数组数组。假设我想计算所有 9 个元素中有多少等于 "a"

string[][] arr = new string[3][] {
    new string[]{"a","b","c"},
    new string[]{"d","a","f"},
    new string[]{"g","a","a"}
};

如何使用 Enumerable 扩展方法(CountWhere 等)来做到这一点?

【问题讨论】:

  • .SelectMany(a => a).Count(a => a == "a")?

标签: c# linq enumerable


【解决方案1】:

您可以使用SelectMany 将所有数组展平为单个字符串序列,然后使用接受谓词的Count 扩展:

arr.SelectMany(a => a).Count(s => s == "a")

【讨论】:

    【解决方案2】:

    您只需要一种方法来遍历矩阵的子元素,您可以使用SelectMany() 完成此操作,然后使用Count()

    int count = arr.SelectMany(x => x).Count(x => x == "a");
    

    制作:

    csharp> arr.SelectMany(x => x).Count(x => x == "a");
    4
    

    或者您可以 Sum() 增加每一行的 Count()s 的计数,例如:

    int count = arr.Sum(x => x.Count(y => y == "a"));
    

    再次生产:

    csharp> arr.Sum(x => x.Count(y => y == "a"));
    4
    

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 2019-06-14
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      相关资源
      最近更新 更多