1

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)?

1
  • 3
    .SelectMany(a => a).Count(a => a == "a")? Commented Jun 15, 2017 at 15:05

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

3

You can flatten all arrays into single sequence of strings with SelectMany and then use Count extension which accepts predicate:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.