- Home /
Array Of Bools
Hello, I was wondering if it was possible to hold an array of booleans and then be able to check if they are false or not in C#. What i wanted to do is have an if statement that says if there all false, then set one true. The thing is im not very familiar with arrays so can someone point me in the right direction for what im looking for?
Thanks For The Help :)
Answer by ZweiD · Feb 21, 2012 at 03:58 PM
just use a for loop:
bool allFalse = true;
bool[] array;
for(int i = 0; i < array.length; i++)
if(!allFalse) break; // allow the loop to end premature
else allFalse = ! array[i];
if(allFalse)
array[0] = true;
is that what you want to do?
It gives me the error "bool[] does not contain a definition for 'length' and no extension method 'length' of type bool[] could be found"
Then it says "are you missing a directive or an assembly reference"
oh right, sorry for that ^.^
now everybody knows that i am a java guy ;)
glad it worked
Answer by HazeTI · Feb 21, 2012 at 05:56 PM
This is quite a good tutorial for arrays in C#. See if it helps you.
Answer by Jessy · Feb 21, 2012 at 05:21 PM
The easiest thing to do is use LINQ. (using System.Linq; at the top of your code):
bool[] array;
if (array.All(b => !b)) //do whatever
Answer by ti89TProgrammer · Feb 21, 2012 at 10:21 PM
You can use one of a couple of methods in the System.Array
class: !Array.Exists(array, item => item)
or Array.TrueForAll(array, item => !item)
. Alternatively, if you put using System.Linq;
at the top of the file, then you can use either array.All(item => !item)
or !array.Any(item => item)
.
The list of booleans more compactly as a BitArray
object (defined in the System.Collections
namespace), in which case either of those last two methods may be used; just replace the array
with bitArray.Cast<bool>()
.
However, if you don’t need to store more than 32 values in the list, then you can achieve greater efficiency by scrapping the use of an actual array completely and instead using an instance of the BitVector32
structure (in the System.Collections.Specialized
namespace); this enables replacing the whole loop with a single constant-time statement:
allFalse = (bitVector.Data == 0);
In this case, if you need to store fewer than 32 values, then you might need an extra variable to store the logical count of booleans.
Your answer
Follow this Question
Related Questions
Saving 30 bools in an array possible? 2 Answers
How do I make ALL other booleans in a bool array false when one is true ? 2 Answers
Distribute terrain in zones 3 Answers
question about array or list of boolean 1 Answer
Initialize Array custom datatype 2 Answers