C#의 Dictionary(딕셔너리)에 키-값 쌍(key-value pair)을 추가하려면 먼저 Dictionary 객체를 선언해야 합니다.
IDictionary<int, string> d = new Dictionary<int, string>();
Dictionary가 준비되면 KeyValuePair 구조체와 Add() 메서드를 사용하여 요소를 하나씩 추가할 수 있습니다.
d.Add(new KeyValuePair<int, string>(1, "TVs"));
d.Add(new KeyValuePair<int, string>(2, "Appliances"));
d.Add(new KeyValuePair<int, string>(3, "Mobile"));
요소 추가가 완료되면 foreach 루프를 통해 저장된 모든 키-값 쌍을 화면에 출력해 볼 수 있습니다.
전체 예제 코드
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
IDictionary<int, string> d = new Dictionary<int, string>();
d.Add(new KeyValuePair<int, string>(1, "TVs"));
d.Add(new KeyValuePair<int, string>(2, "Appliances"));
d.Add(new KeyValuePair<int, string>(3, "Mobile"));
d.Add(new KeyValuePair<int, string>(4, "Tablet"));
d.Add(new KeyValuePair<int, string>(5, "Laptop"));
d.Add(new KeyValuePair<int, string>(6, "Desktop"));
d.Add(new KeyValuePair<int, string>(7, "Hard Drive"));
d.Add(new KeyValuePair<int, string>(8, "Flash Drive"));
foreach (KeyValuePair<int, string> ele in d) {
Console.WriteLine("Key = {0}, Value = {1}", ele.Key, ele.Value);
}
}
}
실행 결과
Key = 1, Value = TVs
Key = 2, Value = Appliances
Key = 3, Value = Mobile
Key = 4, Value = Tablet
Key = 5, Value = Laptop
Key = 6, Value = Desktop
Key = 7, Value = Hard Drive
Key = 8, Value = Flash Drive
위 예제에서는 int 타입의 키와 string 타입의 값을 갖는 Dictionary를 생성했습니다. 참고로 Add() 메서드를 사용할 때 이미 존재하는 키를 다시 추가하려고 하면 ArgumentException 예외가 발생하므로 주의해야 합니다. 키의 중복 여부가 확실하지 않다면 ContainsKey() 메서드로 사전에 확인하거나, .NET Core 2.0 이상에서 제공되는 TryAdd() 메서드를 사용하는 것이 더 안전한 방법입니다.