C#의 제네릭 컬렉션(Generic Collection)은 타입 안정성을 보장하면서 다양한 데이터를 효율적으로 저장하고 관리할 수 있는 자료구조입니다. 대표적인 제네릭 컬렉션으로는 List<T>, SortedList<TKey, TValue>, Dictionary<TKey, TValue> 등이 있습니다.
List<T>
List<T>는 제네릭 컬렉션으로, 비제네릭(non-generic) 컬렉션인 ArrayList와 달리 지정한 타입의 요소만 저장할 수 있습니다. 이 덕분에 잘못된 타입 저장으로 인한 런타임 오류를 예방하고, 박싱(Boxing)·언박싱(Unboxing)에 따른 성능 저하도 피할 수 있습니다.
다음 예제는 문자열 6개를 담은 리스트를 만들고 요소 개수를 출력합니다.
예제 코드
using System;
using System.Collections.Generic;
class Program {
static void Main() {
// 컬렉션 초기화
List<string> myList = new List<string>() {
"one",
"two",
"three",
"four",
"five",
"six"
};
Console.WriteLine(myList.Count);
}
}
출력 결과
6
SortedList<TKey, TValue>
SortedList는 배열(Array)과 해시테이블(Hashtable)의 특성을 결합한 컬렉션입니다. 키(Key) 또는 인덱스(Index)로 항목에 접근할 수 있으며, 항목이 항상 키를 기준으로 정렬된 상태로 유지됩니다.
다음 예제는 4개의 요소를 가진 SortedList를 생성하고, 특정 값이 이미 존재하는지 확인한 후 전체 목록을 출력합니다.
예제 코드
using System;
using System.Collections.Generic;
namespace CollectionsApplication {
class Program {
static void Main(string[] args) {
SortedList<string, string> sl = new SortedList<string, string>();
sl.Add("001", "Tim");
sl.Add("002", "Steve");
sl.Add("003", "Bill");
sl.Add("004", "Tom");
if (sl.ContainsValue("Bill")) {
Console.WriteLine("This name is already in the list");
} else {
sl.Add("005", "James");
}
ICollection<string> keys = sl.Keys;
foreach (string k in keys) {
Console.WriteLine(k + ": " + sl[k]);
}
}
}
}
출력 결과
This name is already in the list 001: Tim 002: Steve 003: Bill 004: Tom
정리
제네릭 컬렉션은 컴파일 시점에 타입을 검사하기 때문에 런타임 오류를 줄여 주고, 불필요한 형 변환과 박싱 비용을 없애 성능까지 향상시킵니다. 단순한 순차 목록이 필요하면 List<T>를, 키-값 쌍을 정렬된 상태로 유지해야 한다면 SortedList<TKey, TValue>를 사용하는 것이 좋습니다.