본문 바로가기

[C#] C#에서의 배열

I'm 영서 2021. 3. 4.
반응형

1차원 배열의 경우 

 

int[] array = new int[5];

 

string[] stringArray = new string[6];

 

int[] array1 = new int[] { 1, 3, 5, 7, 9 };

 

string[] weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

 

2차원 배열

int[,] array = new int[4, 2];

 

3차원배열

int[,,] array1 = new int[4, 2, 3];

// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
                                        { "five", "six" } };

// Three-dimensional array.
int[,,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
                                 { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[,,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } },
                                       { { 7, 8, 9 }, { 10, 11, 12 } } };

// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);

// Getting the total count of elements or the length of a given dimension.
var allLength = array3D.Length;
var total = 1;
for (int i = 0; i < array3D.Rank; i++)
{
    total *= array3D.GetLength(i);
}
System.Console.WriteLine("{0} equals {1}", allLength, total);

// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12
// 12 equals 12

 

동적배열

int[][] jaggedArray = new int[3][];


jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

// jaggedArray
// 0,0,0,0,0
// 0,0,0
// 0,0

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

// jaggedArray
// 1, 3, 5, 7, 9
// 0, 2, 4, 6
// 11, 22


// 이렇게도 초기화 가능하다.
int[][] jaggedArray2 = new int[][]
{
new int[] { 1, 3, 5, 7, 9 },
new int[] { 0, 2, 4, 6 },
new int[] { 11, 22 }
};


//이런 다차원 동적배열도 가능!

int[][,] jaggedArray4 = new int[3][,]
{
    new int[,] { {1,3}, {5,7} },
    new int[,] { {0,2}, {4,6}, {8,10} },
    new int[,] { {11,22}, {99,88}, {0,9} }
};

 

기존 C와 마찬가지로

배열이기 때문에 확장은 불가

반응형

'Study > C#' 카테고리의 다른 글

[C#] Sealed  (0) 2022.04.12
[C#] C#에서 POST방식으로 특정 URL로 데이터 전송  (0) 2022.04.07
[C#] C#에서 DataTable 을 JSON으로 변경  (0) 2022.04.07
[C#] Oracle 연결해서 써먹기  (0) 2021.04.23
[C#] 파일 입출력  (0) 2021.04.19

댓글