计算布尔数组中正确(或错误)元素的数量? [英] calculate number of true (or false) elements in a bool array?

查看:94
本文介绍了计算布尔数组中正确(或错误)元素的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个填充有布尔值的数组,并且我想知道有多少个元素为真.

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 ???
}

如果val为true,则CalculateValues应返回6;如果val为false,则应返回4.

CalculateValues should return 6 if val is true, or 4 if val is false.

明显的解决方案:

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?

推荐答案

使用LINQ.您可以使用testArray.Where(c => c).Count();进行真实计数,或使用testArray.Where(c => !c).Count();进行错误检查

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

这篇关于计算布尔数组中正确(或错误)元素的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆