C# 如何返回二维数组中对象的索引?
我正在处理一个二维的可空布尔数组C# 如何返回二维数组中对象的索引?,c#,boolean,nullable,multidimensional-array,C#,Boolean,Nullable,Multidimensional Array,我正在处理一个二维的可空布尔数组bool?[,]。我正在尝试编写一个方法,从顶部开始,每次循环遍历元素1,对于每个为null的索引,它将返回索引 以下是我到目前为止的情况: public ITicTacToe.Point Turn(bool player, ITicTacToe.T3Board game) { foreach (bool? b in grid) { if (b.HasValue == false) {
bool?[,]
。我正在尝试编写一个方法,从顶部开始,每次循环遍历元素1,对于每个为null的索引,它将返回索引
以下是我到目前为止的情况:
public ITicTacToe.Point Turn(bool player, ITicTacToe.T3Board game)
{
foreach (bool? b in grid)
{
if (b.HasValue == false)
{
}
if (b.Value == null)
{
}
}
return new Point();
}
我希望能够根据传入的bool将对象设置为true/false
Point
只是一个带有x,y
的类
编写此方法的好方法是什么?您应该使用正常的
for
循环,并使用.GetLength(int)
方法
public class Program
{
public static void Main(string[] args)
{
bool?[,] bools = new bool?[,] { { true, null }, { false, true } };
for (int i = 0; i < bools.GetLength(0); i++)
{
for (int j = 0; j < bools.GetLength(1); j++)
{
if (bools[i, j] == null)
Console.WriteLine("Index of null value: (" + i + ", " + j + ")");
}
}
}
}
公共类程序
{
公共静态void Main(字符串[]args)
{
bool?[,]bools=新bool?[,]{{true,null},{false,true};
for(int i=0;i
.GetLength(int)
的参数是维度(即在[x,y,z]
中,应该为维度x
的长度传递0,为y
传递1,为z
传递2)为了好玩,这里有一个使用LINQ和匿名类型的版本。神奇之处在于SelectMany
语句,它将嵌套数组转换为一个匿名类型的IEnumerable
,该匿名类型具有X和Y坐标,并且单元格中的值。我使用的是Select
和SelectMany
的形式,它提供了一个索引,可以方便地获取X和Y
静止的
void Main(string[] args)
{
bool?[][] bools = new bool?[][] {
new bool?[] { true, null },
new bool?[] { false, true }
};
var nullCoordinates = bools.
SelectMany((row, y) =>
row.Select((cellVal, x) => new { X = x, Y = y, Val = cellVal })).
Where(cell => cell.Val == null);
foreach(var coord in nullCoordinates)
Console.WriteLine("Index of null value: ({0}, {1})", coord.X, coord.Y);
Console.ReadKey(false);
}
这很有帮助,谢谢。我对C#还是相当陌生的,这段代码的目的是什么?大多数情况下,我对{true,null}和{false,true}部分感到困惑。bool?[,]bools=新bool?[,]{{true,null},{false,true};