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");
    }
5

Try this:

if (!a.Cast<bool>().All(b => b))
5
  • bool[*,*] does not contain a definition for Any and no extension method Any accepting a first argument of type bool[*,*] could be found. Feb 15, 2014 at 2:24
  • bool[*,*] does not contain a definition for All and no extension method All accepting a first argument of type bool[*,*] could be found. Feb 15, 2014 at 2:25
  • Make sure you have using System.Linq at the top of the file Feb 15, 2014 at 2:25
  • @JoelCoehoorn This only works on one dimensional arrays.
    – Cyral
    Feb 15, 2014 at 2:26
  • 2
    Should be better now. Feb 15, 2014 at 2:29
3
var control = array.OfType<bool>().Contains(false);

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

0
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");
}
1

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.