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

后端 未结 6 1796
深忆病人
深忆病人 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:40

    I like this:

    int trueCount = boolArray.Sum( x  => x ? 1 : 0 ) ;
    
    0 讨论(0)
  • 2021-02-07 00:41

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

    0 讨论(0)
  • 2021-02-07 00:47

    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.

    0 讨论(0)
  • 2021-02-07 00:49

    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);
    
    0 讨论(0)
  • 2021-02-07 00:52
    return testArray.Count(c => c)
    
    0 讨论(0)
  • 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<bool, bool> ifTrue = x => x;
    return testArray.Count(ifTrue);
    
    0 讨论(0)
提交回复
热议问题