calculate number of true (or false) elements in a bool array?

Viewed 36754

Suppose I have an array filled with Boolean values and I want to know how many of the elements are true.

private bool[] testArray = new bool[10] { true, false, true, true, false, true, true, true, false, false };

int CalculateValues(bool val)
{
    return ???
}

CalculateValues should return 6 if val is true, or 4 if val is false.

Obvious solution:

int CalculateValues(bool val)
{
    int count = 0;
    for(int i = 0; i<testArray.Length;i++)
    {
        if(testArray[i] == val)
            count++;
    }
    return count;
}

Is there an "elegant" solution?

6 Answers
Related