2014-03-03 46 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]); 
    } 
}