C#에서 ListDictionary는 키-값 쌍을 저장하는 특수 컬렉션으로, 소규모 데이터 집합을 다룰 때 유용합니다. 이 글에서는 Add() 메서드를 사용하여 ListDictionary에 지정된 키와 값을 추가하는 방법을 예제와 함께 자세히 알아보겠습니다.
ListDictionary.Add() 메서드란?
Add(object key, object value) 메서드는 ListDictionary에 지정된 키와 해당 값을 추가합니다. 만약 동일한 키가 이미 존재한다면 ArgumentException이 발생하므로 주의해야 합니다.
예제 1: 문자열 키-값 쌍 추가하기
다음은 ListDictionary에 여러 개의 키와 값을 추가하고, 열거자(Enumerator)를 사용하여 전체 항목을 출력하는 예제입니다.
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
ListDictionary dict = new ListDictionary();
dict.Add("1", "One");
dict.Add("2", "Two");
dict.Add("3", "Three");
dict.Add("4", "Four");
dict.Add("5", "Five");
Console.WriteLine("ListDictionary 키-값 쌍 출력...");
IDictionaryEnumerator demoEnum = dict.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
}
}실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
ListDictionary 키-값 쌍 출력... Key = 1, Value = One Key = 2, Value = Two Key = 3, Value = Three Key = 4, Value = Four Key = 5, Value = Five
예제 2: 정수 값 추가 후 모든 키 출력하기
이번에는 ListDictionary에 정수형 값을 추가한 뒤, Keys 속성을 통해 저장된 모든 키를 조회하는 예제를 살펴보겠습니다.
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main(){
ListDictionary listDict = new ListDictionary();
listDict.Add("1", 100);
listDict.Add("2", 200);
listDict.Add("3", 300);
listDict.Add("4", 400);
listDict.Add("5", 500);
listDict.Add("6", 600);
listDict.Add("7", 700);
listDict.Add("8", 800);
listDict.Add("9", 900);
listDict.Add("10", 1000);
ICollection col = listDict.Keys;
Console.WriteLine("저장된 모든 키 출력...");
foreach(String s in col){
Console.WriteLine(s);
}
}
}실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
저장된 모든 키 출력... 1 2 3 4 5 6 7 8 9 10
핵심 정리
- Add() 메서드: ListDictionary에 새로운 키-값 쌍을 추가할 때 사용합니다.
- IDictionaryEnumerator:
GetEnumerator()메서드로 얻어 키와 값을 순차적으로 탐색할 수 있습니다. - Keys 속성:
ICollection형태로 모든 키를 반환하여 반복문으로 조회할 수 있습니다. - 주의사항: 중복된 키를 추가하면 ArgumentException이 발생하므로, 필요하다면
Contains()메서드로 키 존재 여부를 먼저 확인하는 것이 좋습니다.
ListDictionary는 내부적으로 단일 연결 리스트 방식으로 구현되어 있어 항목 수가 적을 경우 빠른 성능을 보여줍니다. 따라서 데이터 개수가 많지 않은 상황에서 효율적인 선택이 될 수 있습니다.