2014-03-03 44 views
0

的我已创建了一个对象数组作为这样:打印索引对象

object[,] Values = new object[17, 5]; 

Layer1[0, 0] = neuron1; 
Layer1[1, 0] = neuron1; 
Layer1[2, 0] = neuron2; 

我已经通过对象阵列被写入的功能的循环:

static void Loop_Through_Layer(object[,] Layer1) 
{ 
    //Loop through objects in array 
    foreach (object element in Layer1) 
    { 
     if (element != null) 
     { 
      //Loop through objects in array 
      foreach (object index in Layer1) 
      { 
       if (index != null) 
       { 
        //Need to print indexes of values 
        Console.ReadLine(); 
       } 
      } 
     } 
    } 
} 

我正在尝试这么做,所以通过使用for循环打印对象数组中每个值的位置,但我不确定如何引用这些坐标?

回答

1

你不能用foreach因为它“变平”的阵列 - 你可以用两个普通for循环,而不是:

//Loop through objects in array 
for(int i = 0; i < Layer1.GetLength(0); i++) 
{ 
    for(int j = 0; j < Layer1.GetLength(1); j++) 
    { 
     var element = Layer1[i,j]; 
     if (element != null) 
     { 
      //Need to print indexes of values 
      Console.WriteLine("Layer1[{0},{1}] = {2}", i, j, element); 
+0

谢谢!两种方法都有效。 – user3365114

3

可以使用的范围和for循环来获取值:

for (int x = 0; x < Layer1.GetLength(0); x++) 
{ 
    for (int y = 0; y < Layer1.GetLength(1); y++) 
    { 
     // 
     // You have position x and y here. 
     // 
     Console.WriteLine("At x '{0}' and y '{1}' you have this value '{2}'", x, y, Layer1[x, y]); 
    } 
}