Miguel Moura
Miguel Moura

Reputation: 39364

Check many booleans

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

Answers (4)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

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

StriplingWarrior
StriplingWarrior

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

James Cross
James Cross

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

brz
brz

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

Related Questions