典雅确定是否多于一个的布尔值为"真"
我有一组五个布尔值。如果其中一个以上的是真实的我想excecute一个特定的功能。什么是你能想到的,最优雅的方式,可以让我在一个if()语句检查此条件?目标语言是C#,但我很感兴趣,在其他语言的解决方案(只要我们不是在谈论具体的内置函数)。
I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would allow me to check this condition in a single if() statement? Target language is C# but I'm interested in solutions in other languages as well (as long as we're not talking about specific built-in functions).
一个有趣的选择是将布尔值存储在一个字节中,执行右移,并与原来的字节比较。类似如果(myByte&安培;及(myByte>> 1))(?通过bitArray)
但这需要转换不同的布尔一个字节和似乎有点(双关语意)笨拙... 对不起,本来应该是的如果(myByte及(myByte - 1))
的 [/编辑] 的
One interesting option is to store the booleans in a byte, do a right shift and compare with the original byte. Something like if(myByte && (myByte >> 1))
But this would require converting the separate booleans to a byte (via a bitArray?) and that seems a bit (pun intended) clumsy... [edit]Sorry, that should have been if(myByte & (myByte - 1))
[/edit]
请注意:这当然是非常接近传统的口算,侧身加法还是汉明权重编程问题 - 但不完全一样。我并不需要知道有多少位被置位,仅当它是多台。我希望有一个更简单的实现这种方式。
Note: This is of course very close to the classical "population count", "sideways addition" or "Hamming weight" programming problem - but not quite the same. I don't need to know how many of the bits are set, only if it is more than one. My hope is that there is a much simpler way to accomplish this.
如何
if ((bool1? 1:0) + (bool2? 1:0) + (bool3? 1:0) +
(bool4? 1:0) + (bool5? 1:0) > 1)
// do something
或通用的方法是...
or a generalized method would be...
public bool ExceedsThreshold(int threshold, IEnumerable<bool> bools)
{
int trueCnt = 0;
foreach(bool b in bools)
if (b && (++trueCnt > threshold))
return true;
return false;
}
或使用LINQ由其他答案的建议:
or using LINQ as suggested by other answers:
public bool ExceedsThreshold(int threshold, IEnumerable<bool> bools)
{ return bools.Count(b => b) > threshold; }
编辑(添加乔尔Coehoorn建议:
(在.net 2.x和更高版本)
EDIT (to add Joel Coehoorn suggestion: (in .Net 2.x and later)
public void ExceedsThreshold<T>(int threshold,
Action<T> action, T parameter,
IEnumerable<bool> bools)
{ if (ExceedsThreshold(threshold, bools)) action(parameter); }
或在.net 3.5及更高版本:
or in .Net 3.5 and later:
public void ExceedsThreshold(int threshold,
Action action, IEnumerable<bool> bools)
{ if (ExceedsThreshold(threshold, bools)) action(); }
或作为扩展的IEnumerable&LT;布尔&GT;
public static class IEnumerableExtensions
{
public static bool ExceedsThreshold<T>
(this IEnumerable<bool> bools, int threshold)
{ return bools.Count(b => b) > threshold; }
}
使用然后将:
var bools = new [] {true, true, false, false, false, false, true};
if (bools.ExceedsThreshold(3))
// code to execute ...