我在使用这个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; }
我想知道我怎么能实现if (dead.All(dead[] == true))
?
你可以简单地使用lambda表达式:
if (dead.All(x => x))
鉴于你using System.Linq
的IEnumerable
方法.
会做的.此外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); }
另一个想法,部分借鉴@royhowie如下:
private bool noBricksLeft() { return Enumerable.Range(0,brick.Length).All(i => brickLocation[i,2] == 0); }
是的,你可以使用.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; }