This question already has answers here:
Elegantly determine if more than one boolean is “true”
(22个答案)
7年前关闭。
我在AS3中编写了一个代码,该代码使我可以检查特定数量的事情是否正确……
当我尝试用C#重写时,它告诉我无法添加 boolean 型和 boolean 型。这样做的最好方法是这样重写吗?还是有一些更简单的解决方法?
用法
您还可以介绍
用法
(22个答案)
7年前关闭。
我在AS3中编写了一个代码,该代码使我可以检查特定数量的事情是否正确……
If (true + false + true + true + false + true + true < 4)
{
}
当我尝试用C#重写时,它告诉我无法添加 boolean 型和 boolean 型。这样做的最好方法是这样重写吗?还是有一些更简单的解决方法?
If ((true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) < 4)
{
}
最佳答案
尝试在的 IEnumerable<T>.Count(Func<T,bool>)
方法参数上,使用System.Linq
中的 T
(以bool
作为params
)。
public static int CountTrue(params bool[] args)
{
return args.Count(t => t);
}
用法
// The count will be 3
int count = CountTrue(false, true, false, true, true);
您还可以介绍
this
扩展方法:public static int TrueCount(this bool[] array)
{
return array.Count(t => t);
}
用法
// The count will be 3
int count = new bool[] { false, true, false, true, true }.TrueCount();