I have an array that looks like this:
bool[] array = new bool[4] { true, false, true, true } ;
And I'd like to do an AND/OR comparison between all the elements of this array, something like:
AND example: true AND false AND true AND true
So I can get the final result which would be false in the example above, or:
OR example: true OR false OR true OR true
Which would give me true in the example above.
It there any built-in method in an array that allows me to do it? Or should I have to iterate between all elements and compare them one by one?
As per comments and other answers, you can use LINQ for both of these. (Although you don't have to; farbiondriven's answer will work absolutely fine, although it's less general purpose in that LINQ solutions can handle any IEnumerable<bool>
.)
Any
with an identity projection will detect if any element is true
, which is the same result as performing a logical OR
on all elements.
All
with an identity projection will detect if all elements are true
, which is the same result as performing a logical AND
on all elements:
bool orResult = array.Any(x => x);
bool andResult = array.All(x => x);
Both of these will short-circuit: if the first element is true
, then Any
won't bother looking at later elements, as the result will definitely be true
. Likewise if the first element is false
, then All
won't bother looking at later elements, as the result will definitely be false.
However, you may need to think about what you want the result to be for empty arrays. Any()
will return false
on an empty sequence, whereas All
will return true on an empty sequence. That may or may not be what you expect or need.
See more on this question at Stackoverflow