C#의 SortedList 클래스는 키를 기준으로 자동 정렬되는 키/값 쌍(key-value pair) 컬렉션을 나타냅니다. 이 컬렉션의 가장 큰 특징은 요소에 키뿐만 아니라 인덱스로도 접근할 수 있다는 점입니다.
SortedList는 내부적으로 키 배열과 값 배열을 함께 관리하며, 새로운 요소가 추가될 때마다 정렬 상태를 자동으로 유지합니다. 따라서 데이터를 항상 정렬된 형태로 저장하고 관리해야 하는 상황에서 매우 유용하게 활용할 수 있습니다.
SortedList 클래스의 주요 속성
| 번호 | 속성 및 설명 |
|---|---|
| 1 | Capacity SortedList 개체의 용량(capacity)을 가져오거나 설정합니다. |
| 2 | Count SortedList 개체에 포함된 요소의 개수를 가져옵니다. |
| 3 | IsFixedSize SortedList 개체의 크기가 고정되어 있는지 여부를 나타내는 값을 가져옵니다. |
| 4 | IsReadOnly SortedList 개체가 읽기 전용인지 여부를 나타내는 값을 가져옵니다. |
| 5 | IsSynchronized SortedList 개체에 대한 액세스가 동기화(스레드로부터 안전)되어 있는지 여부를 나타내는 값을 가져옵니다. |
| 6 | Item[Object] SortedList 개체에서 특정 키와 연결된 값을 가져오거나 설정합니다. |
| 7 | Keys SortedList 개체에 포함된 모든 키를 가져옵니다. |
| 8 | SyncRoot SortedList 개체에 대한 액세스를 동기화하는 데 사용할 수 있는 개체를 가져옵니다. |
| 9 | Values SortedList 개체에 포함된 모든 값을 가져옵니다. |
SortedList 클래스의 주요 메서드
| 번호 | 메서드 및 설명 |
|---|---|
| 1 | Add(Object, Object) 지정한 키와 값으로 구성된 요소를 SortedList 개체에 추가합니다. |
| 2 | Clear() SortedList 개체에서 모든 요소를 제거합니다. |
| 3 | Clone() SortedList 개체의 단순 복사본(shallow copy)을 만듭니다. |
| 4 | Contains(Object) SortedList 개체에 특정 키가 포함되어 있는지 여부를 확인합니다. |
| 5 | ContainsKey(Object) SortedList 개체에 특정 키가 포함되어 있는지 여부를 확인합니다. |
| 6 | ContainsValue(Object) SortedList 개체에 특정 값이 포함되어 있는지 여부를 확인합니다. |
| 7 | CopyTo(Array, Int32) 배열의 지정한 인덱스 위치부터 SortedList의 요소를 1차원 Array 개체에 복사합니다. |
| 8 | GetByIndex(Int32) SortedList 개체에서 지정한 인덱스에 해당하는 값을 가져옵니다. |
| 9 | Remove(Object) 지정한 키를 가진 요소를 SortedList 개체에서 제거합니다. |
그럼 몇 가지 예제를 통해 SortedList의 실제 동작을 직접 확인해 보겠습니다.
예제 1: SortedList의 요소 개수 확인하기
다음은 SortedList에 포함된 요소의 개수를 확인하는 코드입니다. 먼저 열 개의 키/값 쌍을 추가한 뒤 Count 속성으로 개수를 출력하고, Clear() 메서드로 모든 요소를 제거한 후 다시 개수를 확인합니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList sortedList = new SortedList();
sortedList.Add("A", "1");
sortedList.Add("B", "2");
sortedList.Add("C", "3");
sortedList.Add("D", "4");
sortedList.Add("E", "5");
sortedList.Add("F", "6");
sortedList.Add("G", "7");
sortedList.Add("H", "8");
sortedList.Add("I", "9");
sortedList.Add("J", "10");
Console.WriteLine("SortedList elements...");
foreach(DictionaryEntry d in sortedList) {
Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
}
Console.WriteLine("Count of SortedList key-value pairs = "+sortedList.Count);
sortedList.Clear();
Console.WriteLine("Count of SortedList (updated) = "+sortedList.Count);
}
}
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
SortedList elements... Key = A, Value = 1 Key = B, Value = 2 Key = C, Value = 3 Key = D, Value = 4 Key = E, Value = 5 Key = F, Value = 6 Key = G, Value = 7 Key = H, Value = 8 Key = I, Value = 9 Key = J, Value = 10 Count of SortedList key-value pairs = 10 Count of SortedList (updated) = 0
출력 결과에서 알 수 있듯이, 키를 A부터 J까지 무작위로 추가했음에도 SortedList는 항상 키 기준으로 정렬된 상태를 유지합니다. 또한 Clear() 호출 후 Count가 0으로 변경된 것을 확인할 수 있습니다.
예제 2: 두 SortedList 개체가 같은지 비교하기
다음은 두 SortedList 개체가 서로 같은지 확인하는 코드입니다. 세 번째 리스트(list3)에 두 번째 리스트(list2)를 할당한 뒤 Equals() 메서드로 두 개체를 비교합니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList list1 = new SortedList();
list1.Add("One", 1);
list1.Add("Two ", 2);
list1.Add("Three ", 3);
list1.Add("Four", 4);
list1.Add("Five", 5);
list1.Add("Six", 6);
list1.Add("Seven ", 7);
list1.Add("Eight ", 8);
list1.Add("Nine", 9);
list1.Add("Ten", 10);
Console.WriteLine("SortedList1 elements...");
foreach(DictionaryEntry d in list1) {
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list2 = new SortedList();
list2.Add("A", "Accessories");
list2.Add("B", "Books");
list2.Add("C", "Smart Wearable Tech");
list2.Add("D", "Home Appliances");
Console.WriteLine("\nSortedList2 elements...");
foreach(DictionaryEntry d in list2) {
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list3 = new SortedList();
list3 = list2;
Console.WriteLine("\nIs SortedList2 equal to SortedList3? = "+list3.Equals(list2));
}
}
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
SortedList1 elements... Eight 8 Five 5 Four 4 Nine 9 One 1 Seven 7 Six 6 Ten 10 Three 3 Two 2 SortedList2 elements... A Accessories B Books C Smart Wearable Tech D Home Appliances Is SortedList2 equal to SortedList3? = True
list3은 list2와 동일한 개체를 참조하므로 Equals() 비교 결과가 True로 반환됩니다. 참고로 첫 번째 리스트의 출력에서도 키가 알파벳 순(Eight, Five, Four...)으로 자동 정렬되어 출력되는 것을 확인할 수 있습니다.
이처럼 C#의 SortedList는 데이터를 항상 정렬된 상태로 유지하면서 키와 인덱스 두 가지 방식으로 요소에 접근할 수 있는 편리한 컬렉션 클래스입니다. 정렬이 필요한 사전(dictionary) 형태의 데이터를 다룰 때 ArrayList나 Hashtable 대신 좋은 선택지가 될 수 있습니다.