EnglischerZauberer
EnglischerZauberer

Reputation: 237

If all elements in bool array are true?

I'm having difficulty using the array.All<> function.

private bool noBricksLeft() {
    bool[] dead = new bool[brick.Length];

    for (int i = 0; i < brick.GetLength(0); i++) {
        if (brickLocation[i, 2] == 0)
            dead[i] = true;
        else
            continue; // move onto the next brick
    }

    if (dead.All(dead[] == true)) // IF ALL OF THE ELEMENTS ARE TRUE
        return true;
    else
        return false;
}

I'm wondering how I can achieve if (dead.All(dead[] == true))?

Upvotes: 16

Views: 30268

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can simply use a lambda-expression:

if (dead.All(x => x))

Given you using System.Linq's IEnumerable<T>.All [msdn] method.

will do the trick. Furthermore an if statement that returns the answer is useless, so you can rewrite it to:

private bool noBricksLeft() {
    bool[] dead = new bool[brick.Length];

    for (int i = 0; i < brick.GetLength(0); i++) {
        if (brickLocation[i, 2] == 0)
            dead[i] = true;
        else
            continue; //move onto the next brick
    }

    return dead.All(x => x);
}

Another idea, partly borrowed from @royhowie is the following:

private bool noBricksLeft() {
    return Enumerable.Range(0,brick.Length).All(i => brickLocation[i,2] == 0);
}

Upvotes: 31

royhowie
royhowie

Reputation: 11171

Yes, you can use .All, but your code still isn't very nice. From what I understand, you can rewrite your code like this, without using an array:

private bool noBricksLeft () {
    for (int i = 0; i < brick.GetLength(0); i++) {
        // inverted your condition; we can short-circuit
        // and just return false
        if (brickLocation[i, 2] != 0)
            return false;
    }
    // every brick passed our condition, so return true
    return true;
}

Upvotes: 8

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can use return dead.All(x => x);

Upvotes: 3

Related Questions