C#에서 SortedDictionary.Item[] 속성은 지정된 키(key)와 연결된 값을 가져오거나 설정하는 데 사용되는 인덱서(indexer) 속성입니다. 이 속성을 활용하면 특정 키에 해당하는 값에 직접 접근할 수 있어 매우 편리합니다.
문법(Syntax)
Item[] 속성의 기본 문법은 다음과 같습니다.
public TValue this[TKey k] { get; set; }여기서 k는 가져오거나 설정할 값의 키를 의미합니다.
예제 1: Item[] 속성으로 값 조회하기
첫 번째 예제를 통해 SortedDictionary에 데이터를 추가하고, Item[] 속성으로 특정 키의 값을 조회하는 방법을 살펴보겠습니다.
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
sortedDict.Add(1, "One");
sortedDict.Add(2, "Two");
sortedDict.Add(3, "Three");
sortedDict.Add(4, "Four");
sortedDict.Add(5, "Five");
sortedDict.Add(6, "Six");
Console.WriteLine("SortedDictionary key-value pairs...");
IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("Count of SortedDictionary key-value pairs = "+sortedDict.Count);
sortedDict.Add(7, "Seven");
sortedDict.Add(8, "Eight");
Console.WriteLine("\nSortedDictionary key-value pairs...UPDATED");
demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("Count of SortedDictionary key-value pairs (UPDATED) = "+sortedDict.Count);
Console.WriteLine("Value in the SortedDictionary key-value pair key five = "+sortedDict[5]);
sortedDict.Clear();
Console.WriteLine("\nCount of SortedDictionary key-value pairs (UPDATED) = "+sortedDict.Count);
}
}실행 결과
Key = 1, Value = One Key = 2, Value = Two Key = 3, Value = Three Key = 4, Value = Four Key = 5, Value = Five Key = 6, Value = Six Count of SortedDictionary key-value pairs = 6 SortedDictionary key-value pairs...UPDATED Key = 1, Value = One Key = 2, Value = Two Key = 3, Value = Three Key = 4, Value = Four Key = 5, Value = Five Key = 6, Value = Six Key = 7, Value = Seven Key = 8, Value = Eight Count of SortedDictionary key-value pairs (UPDATED) = 8 Value in the SortedDictionary key-value pair key five = Five Count of SortedDictionary key-value pairs (UPDATED) = 0
위 예제에서 sortedDict[5]를 사용하여 키가 5인 요소의 값인 "Five"를 성공적으로 조회한 것을 확인할 수 있습니다. 마지막에는 Clear() 메서드로 모든 요소를 제거하여 개수가 0이 된 것도 볼 수 있습니다.
예제 2: Item[] 속성으로 값 수정하기
이번에는 Item[] 속성의 set 기능을 활용해 기존 키의 값을 변경하는 예제를 살펴보겠습니다.
using System;
using System.Collections;
using System.Collections.Generic;
public class Demo {
public static void Main(){
SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
sortedDict.Add(1, "SUV");
sortedDict.Add(2, "MUV");
sortedDict.Add(3, "Utility Vehicle");
sortedDict.Add(4, "AUV");
sortedDict.Add(5, "Hatchback");
sortedDict.Add(6, "Convertible");
Console.WriteLine("SortedDictionary key-value pairs...");
IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("Count of SortedDictionary key-value pairs = "+sortedDict.Count);
sortedDict.Add(7, "Seven");
sortedDict.Add(8, "Eight");
Console.WriteLine("\nSortedDictionary key-value pairs...UPDATED");
demoEnum = sortedDict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("Count of SortedDictionary key-value pairs (UPDATED) = "+sortedDict.Count);
Console.WriteLine("Value in the SortedDictionary key-value pair key five = "+sortedDict[5]);
sortedDict[5] = "Crossover";
Console.WriteLine("Value in the SortedDictionary key-value pair key five (updated) = "+sortedDict[5]);
sortedDict.Clear();
Console.WriteLine("\nCount of SortedDictionary key-value pairs (UPDATED) = "+sortedDict.Count);
}
}실행 결과
SortedDictionary key-value pairs... Key = 1, Value = SUV Key = 2, Value = MUV Key = 3, Value = Utility Vehicle Key = 4, Value = AUV Key = 5, Value = Hatchback Key = 6, Value = Convertible Count of SortedDictionary key-value pairs = 6 SortedDictionary key-value pairs...UPDATED Key = 1, Value = SUV Key = 2, Value = MUV Key = 3, Value = Utility Vehicle Key = 4, Value = AUV Key = 5, Value = Hatchback Key = 6, Value = Convertible Key = 7, Value = Seven Key = 8, Value = Eight Count of SortedDictionary key-value pairs (UPDATED) = 8 Value in the SortedDictionary key-value pair key five = Hatchback Value in the SortedDictionary key-value pair key five (updated) = Crossover Count of SortedDictionary key-value pairs (UPDATED) = 0
정리
이번 글에서는 C# SortedDictionary의 Item[] 속성을 활용하는 방법을 알아보았습니다. 핵심 내용은 다음과 같습니다.
- 값 조회(get):
sortedDict[키]형태로 해당 키에 연결된 값을 읽어올 수 있습니다. - 값 설정(set):
sortedDict[키] = 새로운값형태로 기존 키의 값을 간단히 변경할 수 있습니다. - 주의 사항: 존재하지 않는 키로 값을 조회하면 KeyNotFoundException이 발생할 수 있으므로, 필요하다면
TryGetValue나ContainsKey메서드를 함께 사용하는 것이 안전합니다.
SortedDictionary는 키를 기준으로 자동 정렬된 상태를 유지하는 컬렉션이므로, 정렬된 순서로 데이터를 관리해야 하는 경우에 유용하게 활용할 수 있습니다.