2012-08-30 30 views
1

我有一個非常愚蠢的問題。請原諒它晚了,我累了。 :)獲取2d陣列中二維數組的數量

我有定義整數的2D陣列如下:

int[,] myArray = new int[,] // array of 7 int[,] arrays 
{ 
    { 1, 10 }, // 0 
    { 2, 20 }, // 1 
    { 3, 30 }, // 2 
    { 4, 40 }, // 3 
    { 5, 50 }, // 4 
    { 6, 60 }, // 5 
    { 7, 70 }, // 6     
}; 

正如可以看到陣列由7 INT [,]陣列。

當我打電話myArray.Length它的結果是14.我需要的是7.如何獲得int [,]數組的數量?什麼是調用方法(我期待的結果是7)。

再次感謝!

回答

2

不是二維數組的數組 - 它是一個二維數組。如前所述,尺寸由myArray.GetLength(dimension)給出。它不是一個具有「7 int [,]數組」的數組 - 它只是一個7乘2的數組。

如果要數組的數組(實際上,載體的載體中),它是:

int[][] myArray = { 
    new int[] {1,10}, // alternative: new[]{1,10} - the "int" is optional 
    new int[] {2,20}, 
    new int[] {3,30}, 
    new int[] {4,40}, 
    new int[] {5,50}, 
    new int[] {6,60}, 
    new int[] {7,70}, 
}; 

然後7myArray.Length是。

+0

非常感謝! –

+0

我喜歡這種方式!我想我會用你的建議看起來更優雅! :) –

5

使用GetLength方法來獲得一維的長度。

myArray.GetLength(0) 

嘗試下面幾行:

Console.WriteLine(myArray.GetLength(0)); 
Console.WriteLine(myArray.GetLength(1)); 

你會得到

7 
2 
+0

啊!這就是謝謝:) –

+0

@JanTacci,不客氣 – Habib