C#에서 AddRange() 메서드를 활용하면 두 개의 배열을 손쉽게 하나로 병합할 수 있습니다. 이 방법은 배열을 직접 합치는 대신, 중간 단계로 List<T>를 활용하는 것이 핵심입니다.
병합 절차
1단계: 두 개의 배열 선언
먼저 병합할 두 개의 배열을 준비합니다.
int[] arr1 = { 15, 20, 27, 56 };
int[] arr2 = { 62, 69, 76, 92 };2단계: 리스트 생성 후 AddRange()로 요소 추가
새로운 List<int>를 만들고, AddRange() 메서드를 사용해 각 배열의 모든 요소를 순서대로 추가합니다.
var myList = new List<int>(); myList.AddRange(arr1); myList.AddRange(arr2);
AddRange()는 컬렉션 전체를 한 번에 추가할 수 있어 요소를 하나씩 반복문으로 넣는 것보다 효율적입니다.
3단계: 병합된 컬렉션을 배열로 변환
마지막으로 ToArray() 메서드를 호출하여 리스트를 다시 배열 형태로 변환합니다.
int[] arr3 = myList.ToArray();
전체 예제 코드
지금까지의 과정을 하나의 완성된 프로그램으로 정리하면 다음과 같습니다.
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
int[] arr1 = { 15, 20, 27, 56 };
int[] arr2 = { 62, 69, 76, 92 };
// 첫 번째 배열 출력
Console.WriteLine("Array 1...");
foreach(int ele in arr1) {
Console.WriteLine(ele);
}
// 두 번째 배열 출력
Console.WriteLine("Array 2...");
foreach(int ele in arr2) {
Console.WriteLine(ele);
}
// AddRange()로 두 배열 병합
var myList = new List<int>();
myList.AddRange(arr1);
myList.AddRange(arr2);
int[] arr3 = myList.ToArray();
// 병합 결과 출력
Console.WriteLine("Merged array..");
foreach (int res in arr3) {
Console.WriteLine(res);
}
}
}실행 결과
Array 1... 15 20 27 56 Array 2... 62 69 76 92 Merged array.. 15 20 27 56 62 69 76 92
정리
이처럼 AddRange() 메서드와 List<T>를 조합하면 반복문 없이도 간결하게 두 배열을 병합할 수 있습니다. 참고로 C#에서는 LINQ의 Concat() 메서드나 CopyTo()를 이용한 방법으로도 배열을 합칠 수 있으므로, 상황에 맞게 선택하여 사용하면 됩니다.