C#의 SortedList는 키를 기준으로 자동 정렬되는 키/값 쌍 컬렉션입니다. SortedList에 새로운 키/값 쌍을 추가하려면 Add(object key, object value) 메서드를 사용합니다. 이 메서드는 첫 번째 매개변수로 키를, 두 번째 매개변수로 값을 받습니다.
단, 이미 존재하는 키를 다시 추가하려고 하면 ArgumentException 예외가 발생하므로 주의해야 합니다.
예제 1 – Add() 메서드로 요소 추가 후 Keys와 Values 확인
다음은 Add() 메서드로 여러 개의 키/값 쌍을 추가한 뒤, Values와 Keys 컬렉션을 각각 출력하는 예제입니다.
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args){
SortedList list = new SortedList();
list.Add("A", "Jacob");
list.Add("B", "Sam");
list.Add("C", "Tom");
list.Add("D", "John");
list.Add("E", "Tim");
list.Add("F", "Mark");
list.Add("G", "Gary");
list.Add("H", "Nathan");
list.Add("I", "Shaun");
list.Add("J", "David");
ICollection col1 = list.Values;
Console.WriteLine("Values...");
foreach(string s in col1)
Console.WriteLine(s);
ICollection col2 = list.Keys;
Console.WriteLine("\nKeys...");
foreach(string s in col2)
Console.WriteLine(s);
}
}출력 결과
위 코드를 실행하면 다음과 같은 출력이 생성됩니다 −
Values... Jacob Sam Tom John Tim Mark Gary Nathan Shaun David Keys... A B C D E F G H I J
예제 2 – DictionaryEntry로 전체 요소 출력 및 RemoveAt() 활용
이번에는 DictionaryEntry 구조체를 사용하여 SortedList의 모든 키/값 쌍을 출력하고, RemoveAt() 메서드로 특정 인덱스의 요소를 삭제한 후 열거자(IDictionaryEnumerator)로 다시 순회하는 예제를 살펴보겠습니다.
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.RemoveAt(3);
Console.WriteLine("\nEnumerator to iterate through the SortedList...");
IDictionaryEnumerator demoEnum = sortedList.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("Count of SortedList key-value pairs (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 Enumerator to iterate through the SortedList... Key = A, Value = 1 Key = B, Value = 2 Key = C, Value = 3 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 (Updated) = 9
핵심 정리
Add(key, value): SortedList에 키/값 쌍을 추가하며, 내부적으로 키 순서에 맞게 자동 정렬됩니다.RemoveAt(index): 지정된 인덱스 위치의 요소를 제거합니다.Count: 현재 SortedList에 포함된 키/값 쌍의 개수를 반환합니다.IDictionaryEnumerator: SortedList의 요소를 순차적으로 탐색할 때 사용합니다.