Search code examples
c#linqenumerable

Count elements in array of arrays equal to specified value


I have array of arrays. Suppose I want to count how much elements out of all 9 is equal to "a".

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

How can I do it using Enumerable extension methods (Count, Where, etc)?


Solution

  • You simply need a way to iterate over the subelements of the matrix, you can do this using SelectMany(), and then use Count():

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

    Producing:

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

    Or you could Sum() up the counts of the Count()s of each individual row, like:

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

    Producing again:

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