我有4个布尔值,它可以是一个,也可以是多个的组合,也可以没有。我的最终输出是,我知道哪些bools设置为true。
例如:仅一个仅一和二个仅一、二和三个全部二、三、四个仅二和三,依此类推。
我一开始是用If-语句手动写出这些代码,但后来我开始意识到:1:这段代码看起来很混乱。2:这个方法要花很多功夫。一定有更好的方法可以做到这一点,对吧?
如果您有布尔值集合,例如
bool[] flags = new bool[] {
first,
second,
third,
...
last
};
您可以在Linq:的帮助下查询它们
using System.Linq;
...
if (flags.All(x => x)) {
// if all booleans are true
}
if (flags.Count(x => x) == 2) {
// if exactly two booleans are true
}
if (flags.Count(x => x) >= 3) {
// if at least 3 booleans are true
}
if (flags.Count(x => x) <= 4) {
// if at most 4 booleans are true
}
if (flags.Any(x => x)) {
// if at least 1 boolean is true;
// it can be done with a help of Count, but Any is more readable
}
如果您想像Dmitary的答案所建议的那样,除了bool
值之外,还用某种名称输出它们,请将名称添加为文本:
var flags = new[]
{
new { Value = one, Name = nameof(one)},
new { Value = two, Name = nameof(two)},
new { Value = three, Name = nameof(three) }
};
var trueCount = flags.Count(x => x.Value);
var names = String.Join(",", flags.Where(x => x.Value).Select(x => x.Name));
if (trueCount == 0) return $"none";
if (trueCount == 1) return $"just {names}";
else if (trueCount < flags.Length) return $"only {names}";
else return $"all {names}";
注意:如果您想做的不仅仅是计算真/假,那么切换到[Flags]
枚举可能会很有用。或者考虑切换到Dictionary<string, bool>
。