2D布尔数组,检查数组是否包含false。

4

我在C#中使用了一个二维布尔数组。我查阅了dot net pearls上的Array.Exists函数,但我无法让它工作,可能是因为我使用了布尔值或者因为这是一个二维数组。

bool[,] array = new bool[4, 4];

if (array.Contains(false)) {}; // This line is pseudo coded to show what I'm looking for
5个回答

6

我不知道这是否是正确的方法,但对每个元素进行强制转换似乎是有效的:

bool[,] a = new bool[4,4]
    {
        {true, true, true, true},
        {true, true, false, true},
        {true, true, true, true},
        {true, true, true, true},
    };

    if(a.Cast<bool>().Contains(false))
    {
        Console.Write("Contains false");
    }

5

试试这个:

if (!a.Cast<bool>().All(b => b))

bool[*,*] 不包含 Any 的定义,也没有找到接受类型为 bool[*,*] 的第一个参数的 Any 扩展方法。 - Enigmativity
bool[*,*] 不包含 All 的定义,也没有找到接受类型为 bool[*,*] 的第一个参数的 All 扩展方法。 - Enigmativity
确保你在文件顶部有 using System.Linq - Joel Coehoorn
@JoelCoehoorn 这仅适用于一维数组。 - Cyral
2
现在应该会更好。 - Joel Coehoorn

3
var control = array.OfType<bool>().Contains(false);

当您使用多维数组时,始终可以使用OfType方法。它非常有用。


2
使用LINQ的(using System.Linq;)OfTypeCast数组扩展,可以测试每个数组元素是否为true,如果不是,则可用于触发事件。
a[0,0] = false; //Change this to test
if (!a.OfType<bool>().All(x => x))
{
     Console.Write("Contains A False Value");
     //Do Stuff
}
else
{
     Console.Write("Contains All True Values");
}

1
尝试像这样: if (array.ToList().Contains(false)) 一般来说,如果效率不是那么重要,转换为列表非常有用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接