4

I'm using a 2D array of booleans in C#. I've looked up the Array.Exists function at dot net pearls but I can't get it to work, either because I'm using booleans or because it's a 2D array.

bool[,] array = new bool[4, 4]; if (array.Contains(false)) {}; // This line is pseudo coded to show what I'm looking for 

5 Answers 5

6

Don't know if this is the proper way or not but casting each element seems to work:

bool[,] a = new bool[4,4] { {true, true, true, true}, {true, true, false, true}, {true, true, true, true}, {true, true, true, true}, }; if(a.Cast<bool>().Contains(false)) { Console.Write("Contains false"); } 
Sign up to request clarification or add additional context in comments.

Comments

5

Try this:

if (!a.Cast<bool>().All(b => b)) 

5 Comments

bool[*,*] does not contain a definition for Any and no extension method Any accepting a first argument of type bool[*,*] could be found.
bool[*,*] does not contain a definition for All and no extension method All accepting a first argument of type bool[*,*] could be found.
Make sure you have using System.Linq at the top of the file
@JoelCoehoorn This only works on one dimensional arrays.
Should be better now.
3
var control = array.OfType<bool>().Contains(false); 

You can always use OfType method when you working with multidimensional arrays.It's very useful.

Comments

2

Using LINQ's (using System.Linq;) OfType or Cast array extensions allows you to test if each array element is true, and if not can be used to fire your event.

a[0,0] = false; //Change this to test if (!a.OfType<bool>().All(x => x)) { Console.Write("Contains A False Value"); //Do Stuff } else { Console.Write("Contains All True Values"); } 

Comments

1

Try like this: if (array.ToList().Contains(false))

Generally speaking if efficiency is not that needed then converting to list is very useful

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.