Reputation: 39364
I have many Boolean variables as follows:
Boolean A;
Boolean B;
Boolean C;
Boolean D;
Boolean E;
Boolean F;
...
I would like to make sure all them are false or, at most, only one is true.
Is there a fast way to do this without using a lot of IFs?
Upvotes: 0
Views: 187
Reputation: 11910
unsigned long var64 = (X & A<<1 & B<<2 & C<<3 .... Z <<63)+1
makes var64 zero if all true if os and project and cpu is 64 bit x64;
Upvotes: 0
Reputation: 156469
Yes. Put all of the booleans into a list, and then use the .All()
or .Any()
extension methods.
var options = new List<bool>{A, B, C, D, E, F, etc.};
var allAreFalse = options.All(b => !b);
var atLeastOneIsTrue = options.Any(b => b);
var moreThanOneIsTrue = options.Where(b => b).Skip(1).Any();
PS--It's likely that you don't actually want to declare all of these booleans as separate variables in the first place. Code like that usually indicates that you are representing data as code, and should be using data structures to represent and manipulate those values.
Upvotes: 15
Reputation: 7859
boolean[] bools = new boolean[...];
// add all bools to list
if (!bools.All()) {
// All are false
}
if (bools.Any()){
// One or more are true
}
Upvotes: 0
Reputation: 6016
Add them to a list and count the true values:
var lst = new[] { A, B, C, D, E };
var res = lst.Count(x=>x) <= 1;
Upvotes: 6