【问题标题】:how can I return the index of an object in a 2 dimensional array?如何在二维数组中返回对象的索引?
【发布时间】:2011-04-25 17:46:44
【问题描述】:

我正在使用可以为空的布尔值 bool?[,] 的二维数组。我正在尝试编写一个方法,从顶部开始一次循环遍历其元素 1,并且对于每个为空的索引,它将返回索引。

这是我目前所拥有的:

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();

 }

我希望能够根据传入的布尔值将对象设置为true/falsePoint 只是一个带有x,y 的类。

写这个方法的好方法是什么?

【问题讨论】:

  • 这很有帮助,谢谢。我对 C# 还是很陌生,这段代码的目的是什么?大多数情况下,我对 {true,null} 和 {false, true} 部分感到困惑。 bool?[,] bools = new bool?[,] { { true, null }, { false, true } };

标签: c# boolean nullable multidimensional-array


【解决方案1】:

只是为了好玩,这里有一个使用 LINQ 和匿名类型的版本。神奇之处在于 SelectMany 语句,它将我们的嵌套数组转换为具有 X 和 Y 坐标以及单元格中的值的匿名类型的 IEnumerable<>。我正在使用SelectSelectMany 的形式,它提供了一个索引以便于获取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);
 }

【讨论】:

    【解决方案2】:

    您应该使用普通的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 + ")");
                }
            }
        }
    }
    

    .GetLength(int) 的参数是维度(即在[x,y,z] 中,您应该为维度x 的长度传递0,为y 传递1,为z 传递2。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-27
      • 2015-01-29
      • 2017-11-09
      • 1970-01-01
      • 2017-08-16
      • 2015-04-20
      • 2021-05-01
      • 1970-01-01
      相关资源
      最近更新 更多