2차원 배열 선언 -
string[,] array = new string[3, 3];
배열의 요소 설정 -
array[0, 0] = "One"; array[0, 1] = "Two"; array[0, 2] = "Three"; array[1, 0] = "Four"; array[1, 1] = "Five"; array[1, 2] = "Six"; array[2, 0] = "Seven"; array[2, 1] = "Eight"; array[2, 2] = "Nine";
이제, 배열을 반복할 차원을 얻기 위해 상한값을 구하십시오 -
int uBound0 = array.GetUpperBound(0); int uBound1 = array.GetUpperBound(1);
아래 코드와 같이 위의 두 값이 표시될 때까지 중첩 루프를 반복합니다. -
예시
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
public static void Main() {
string[,] array = new string[3, 3];
array[0, 0] = "One";
array[0, 1] = "Two";
array[0, 2] = "Three";
array[1, 0] = "Four";
array[1, 1] = "Five";
array[1, 2] = "Six";
array[2, 0] = "Seven";
array[2, 1] = "Eight";
array[2, 2] = "Nine";
// getting upper bound
int uBound0 = array.GetUpperBound(0);
int uBound1 = array.GetUpperBound(1);
for (int i = 0; i <= uBound0; i++) {
for (int j = 0; j <= uBound1; j++) {
string res = array[i, j];
Console.WriteLine(res);
}
}
Console.ReadLine();
}
} 출력
One Two Three Four Five Six Seven Eight Nine