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, t
I like this:
int trueCount = boolArray.Sum( x => x ? 1 : 0 ) ;
Use LINQ. You can do testArray.Where(c => c).Count();
for true count or use testArray.Where(c => !c).Count();
for false check
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.
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);
return testArray.Count(c => c)
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);