Juicy
Juicy

Reputation: 12500

2D boolean array, check if array contains a false

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

Upvotes: 4

Views: 2480

Answers (5)

Selman Genç
Selman Genç

Reputation: 101681

var control = array.OfType<bool>().Contains(false);

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

Upvotes: 3

Cyral
Cyral

Reputation: 14153

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

Upvotes: 2

Joel Coehoorn
Joel Coehoorn

Reputation: 415630

Try this:

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

Upvotes: 5

Michał
Michał

Reputation: 2282

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

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

Upvotes: 1

pcnThird
pcnThird

Reputation: 2372

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

Upvotes: 6

Related Questions