如果bool数组中的所有元素都为真?

Eng*_*rer 11 c# arrays

我在使用这个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.LinqIEnumerable<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”并不奇怪。如果至少有一个匹配元素,则 `Any(pred)` 为真,如果有至少一个元素,则 `Any()` 为真,否则为假,所以它本质上是 `Any(x =&gt; true)`,。如果至少有一个不匹配的元素,则 `All(pred)` 为 false,因此同样等价于 `All(x =&gt; true)` 的 `All()` 将始终返回 true。 (2认同)

roy*_*wie 7

是的,你可以使用.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)

  • 虽然我和CommuSoft的答案集中在使用all的正确语法上,但您的答案对于指导OP正确编写其方法的方法也很有用.+1给你的答案:) (2认同)