建立三維陣列的方法
/*方法1*/ //不指定維度 int[, ,] a = new int[, , ] { {{ 1, 2, 3 }, { 4, 5, 6 } ,{ 3, 1, 2 },{ 7, 2, 3 }}, {{ 7, 8, 9 }, { 8, 9, 0 } ,{ 3, 1, 2 },{ 2, 1, 4 }} }; /*方法2*/ //指定維度,第一維2,第二維4,第三維3 int[, ,] a = new int[2, 4, 3] { {{ 1, 2, 3 }, { 4, 5, 6 } ,{ 3, 1, 2 },{ 7, 2, 3 }}, {{ 7, 8, 9 }, { 8, 9, 0 } ,{ 3, 1, 2 },{ 2, 1, 4 }} };
可以想成如下的圖,想像是一棟房子
第一維的2,表示共有前、後二棟樓黏在一起(有二組中括號),
第二維的4,表示每棟有四樓(中括號中又各有四個中括號)
第三維的3,表示每樓有三戶(每個括號有3個數字)
圖片來源:旗標知識網 http://www.flag.com.tw/book/cento-5105.asp?bokno=F2733&id=980
第一個[0]代表第一棟樓,後面和二維陣列一模一樣
a[0] [0][0]=1,a[0] [0][1]=2,a[0] [0][2]=3
a[0] [1][0]=4,a[0] [1][1]=5,a[0] [1][2]=6
a[0] [2][0]=3,a[0] [2][1]=1,a[0] [2][2]=2
a[0] [3][0]=7,a[0] [3][1]=2,a[0] [3][2]=3
第一個[1]代表第二棟樓,後面和二維陣列一模一樣
a[1] [0][0]=7,a[1] [0][1]=8,a[1] [0][2]=9
a[1] [1][0]=8,a[1] [1][1]=9,a[1] [1][2]=0
a[1] [2][0]=3,a[1] [2][1]=1,a[1] [2][2]=2
a[1] [3][0]=2,a[1] [3][1]=1,a[1] [3][2]=4
三維陣列的存取
假設有一3x2x3維陣列如下 //共有3棟樓,每棟樓有2層樓,每層有3戶 int[, ,] arr2 = new int[3, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 }}, { { 7, 8, 9 }, { 10, 11, 12 }}, { { 13,14,15 },{ 16, 17, 18 }} }; /*方法1*/ //直接存取陣列元素 Response.Write(arr2[1, 1, 2]); /*方法2*/ //GetUpperBound方法--取得陣列中某一維度上限 //arr2.GetUpperBound(0)->2 第一維上限是2 //arr2.GetUpperBound(1)->1 第二維上限是1 //arr2.GetUpperBound(2)->2 第三維上限是2 for (int i = 0; i <= arr2.GetUpperBound(0); i++) { for (int j = 0; j <= arr2.GetUpperBound(1); j++) { for (int z = 0; z <= arr2.GetUpperBound(2); z++) { Response.Write(arr2[i, j, z].ToString()); } } } /*方法3*/ //GetLength方法--取得某一維度的長度(即元素個數) //arr2.GetLength(0)->3 //arr2.GetLength(1)->2 //arr2.GetLength(2)->3 for (int i = 0; i <= arr2.GetLength(0)-1; i++) { for (int j = 0; j <= arr2.GetLength(1)-1; j++) { for (int z = 0; z <= arr2.GetLength(2)-1; z++) { Response.Write(arr2[i, j, z].ToString()); } } } /*方法4*/ //用foreach廻圈 foreach (int i in arr2) // foreach (資料型別 i in 集合物件) { Response.Write(i); } //註:arr2.Length會得到元素總個數18
資料來源:
MSDN 陣列教學課程(2003)http://msdn.microsoft.com/zh-TW/library/aa288453(v=vs.71).aspx
MSDN 多維陣列(2012)http://msdn.microsoft.com/zh-tw/library/2yd9wwz4.aspx
綠色進行式:[C#] 陣列(Array)基本用法 http://blog.yehyeh.net/?p=525
c# 中使用foreach和for遍历 一维数组; 二维数组; 交错数组 http://zhidao.baidu.com/question/214951707.html
圖解說三維陣列 http://www.flag.com.tw/book/cento-5105.asp?bokno=F2733&id=980