我在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
我在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
我不知道这是否是正确的方法,但对每个元素进行强制转换似乎是有效的:
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");
}
试试这个:
if (!a.Cast<bool>().All(b => b))
using System.Linq;
)OfType
或Cast
数组扩展,可以测试每个数组元素是否为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");
}
if (array.ToList().Contains(false))
一般来说,如果效率不是那么重要,转换为列表非常有用。
bool[*,*]
不包含Any
的定义,也没有找到接受类型为bool[*,*]
的第一个参数的Any
扩展方法。 - Enigmativitybool[*,*]
不包含All
的定义,也没有找到接受类型为bool[*,*]
的第一个参数的All
扩展方法。 - Enigmativityusing System.Linq
。 - Joel Coehoorn