C# 计算布尔数组中真(或假)元素的数量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11730912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
calculate number of true (or false) elements in a bool array?
提问by Evgeny
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.
如果 val 为真,CalculateValues 应返回 6,如果 val 为假,则应返回 4。
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?
有没有“优雅”的解决方案?
采纳答案by Chris Knight
Use LINQ. You can do testArray.Where(c => c).Count();for true count or use testArray.Where(c => !c).Count();for false check
使用 LINQ。您可以testArray.Where(c => c).Count();进行真实计数或testArray.Where(c => !c).Count();用于错误检查
回答by SLaks
return testArray.Count(c => c)
回答by Reed Copsey
You can use:
您可以使用:
int CalculateValues(bool val)
{
return testArray.Count(c => c == val);
}
This handles the trueand falsechecks, based on your valparameter.
这将根据您的参数处理true和false检查val。
回答by DeanG
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);
回答by Nicholas Carey
I like this:
我喜欢这个:
int trueCount = boolArray.Sum( x => x ? 1 : 0 ) ;
回答by Matthew Strawbridge
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 => cpart thinking it doesn't do anything.
虽然testArray.Count(c => c)在功能上是正确的,但它并不直观,并且存在一些后来的开发人员会c => c认为它不做任何事情而剥离该部分的风险。
This can be derisked by declaring the lambda function separately with a meaningful name:
这可以通过使用有意义的名称单独声明 lambda 函数来消除:
Func<bool, bool> ifTrue = x => x;
return testArray.Count(ifTrue);

