计算数组数组中等于指定值的元素

Count elements in array of arrays equal to specified value

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

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

如何使用可枚举扩展方法(CountWhere 等)?

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

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

您只需要一种方法来遍历矩阵的 子元素 ,您可以使用 SelectMany(), and then use Count():

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

制作中:

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

或者您可以 Sum() up the counts of the Count() 每一行,例如:

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

再次生产:

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