我在使用这个array.All<>功能时遇到了困难.
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;
}
Run Code Online (Sandbox Code Playgroud)
我想知道我怎么能实现if (dead.All(dead[] == true))?
Wil*_*sem 19
你可以简单地使用lambda表达式:
if (dead.All(x => x))
Run Code Online (Sandbox Code Playgroud)
鉴于你using System.Linq的IEnumerable<T>.All方法.
会做的.此外if,返回答案的语句是无用的,因此您可以将其重写为:
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);
}
Run Code Online (Sandbox Code Playgroud)
另一个想法,部分借鉴@royhowie如下:
private bool noBricksLeft() {
return Enumerable.Range(0,brick.Length).All(i => brickLocation[i,2] == 0);
}
Run Code Online (Sandbox Code Playgroud)
是的,你可以使用.All,但你的代码仍然不是很好.据我所知,您可以像这样重写代码,而无需使用数组:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8099 次 |
| 最近记录: |