有没有办法在 C# 中检测多个布尔值的一个、组合或 none?
Is there a way to detect one, a combination, or none of multiple boolean values in C#?
我有 4 个布尔值,它可以是一个,多个的组合,或者 none。我的最终输出是,我知道哪些布尔值被设置为真。
例如:仅一/仅一二/仅一二和三个/全部一、二、三、四/仅二和三/等等..
我开始是使用 If - 语句手动写出这些内容,但后来我开始意识到:1:这段代码看起来很混乱。 2:这个方法会很费功夫 3.一定有更好的方法吧?
如果您有集合 布尔值,例如
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
}
如果您想要输出它们,除了 bool
值之外,还要按照 Dmitiry 的建议添加名称作为文本:
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}";
注意:如果您想做的不仅仅是计数 true/false,切换到 [Flags]
枚举可能会很有用。或者考虑切换到 Dictionary<string, bool>
.
我有 4 个布尔值,它可以是一个,多个的组合,或者 none。我的最终输出是,我知道哪些布尔值被设置为真。
例如:仅一/仅一二/仅一二和三个/全部一、二、三、四/仅二和三/等等..
我开始是使用 If - 语句手动写出这些内容,但后来我开始意识到:1:这段代码看起来很混乱。 2:这个方法会很费功夫 3.一定有更好的方法吧?
如果您有集合 布尔值,例如
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
}
如果您想要输出它们,除了 bool
值之外,还要按照 Dmitiry
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}";
注意:如果您想做的不仅仅是计数 true/false,切换到 [Flags]
枚举可能会很有用。或者考虑切换到 Dictionary<string, bool>
.