Reputation: 237
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
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
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