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

后端 未结 6 1788
深忆病人
深忆病人 2021-02-07 00:15

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         


        
6条回答
  •  独厮守ぢ
    2021-02-07 00:58

    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 ifTrue = x => x;
    return testArray.Count(ifTrue);
    

提交回复
热议问题