2017-06-15 58 views
1

我有數組數組。假設我想統計出9箇中有多少元素等於"a"數組中的元素的數量等於指定值

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

我如何使用可枚舉擴展方法(CountWhere等),它做什麼?

+3

'.SelectMany(A => A)。 Count(a => a ==「a」)'? – CodeCaster

回答

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 
3

您可以拼合所有陣列成字符串的單個序列與SelectMany然後用Count擴展,它接受斷言:

arr.SelectMany(a => a).Count(s => s == "a") 
相關問題