29

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Evgeny
  • 3,320
  • 7
  • 39
  • 50

6 Answers6

58
return testArray.Count(c => c)
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
42

Use LINQ. You can do testArray.Where(c => c).Count(); for true count or use testArray.Where(c => !c).Count(); for false check

Chris Knight
  • 1,448
  • 1
  • 15
  • 21
16

You can use:

int CalculateValues(bool val)
{
    return testArray.Count(c => c == val);
}

This handles the true and false checks, based on your val parameter.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

While testArray.Count(c => c) is functionally correct, it's not intuitive and there's a risk that some later developer will strip out the c => c part thinking it doesn't do anything.

This can be derisked by declaring the lambda function separately with a meaningful name:

Func<bool, bool> ifTrue = x => x;
return testArray.Count(ifTrue);
Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
2

Try something like this :

bool[] testArray = new bool[10] { true, false, true, true, false, true, true, true, false, false };
bool inVal = true;
int i;

i = testArray.Count(ai => ai == inVal);
DeanG
  • 617
  • 4
  • 6
-2

I like this:

int trueCount = boolArray.Sum( x  => x ? 1 : 0 ) ;
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • 1
    Why repurpose `Sum` to perform the function of `Count`? – Richard Jul 31 '12 at 08:10
  • Because it's simpler, more concise and to the point. If you like `Where()`/`Count()`, you get the same results at the expense of an additional method call per array element. – Nicholas Carey Jul 31 '12 at 16:40
  • 2
    I'd say `int trueCount = boolArray.Count(x => x)` is much more concise and to the point – Richard Jul 31 '12 at 16:48
  • According to the documentation, `Count()` "Returns the number of elements in a sequence." That will give you the count of the number of elements in the array or in the `IEnumerable`, regardless of the element's _value_: you need to filter the sequence with `Where()` prior to applying `Count()`. – Nicholas Carey Jul 31 '12 at 17:10
  • 5
    The `.Count()` method on a collection does, yes. The `.Count` extension method in LINQ can take a filter: http://msdn.microsoft.com/en-us/library/bb534807(v=vs.110).aspx – Richard Jul 31 '12 at 17:12