Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# SortedDictionary.Add() 메서드 – 키-값 쌍 추가 방법과 예제

C#의 SortedDictionary.Add() 메서드는 지정한 키(key)와 값(value)으로 이루어진 요소를 SortedDictionary<TKey, TValue> 컬렉션에 추가하는 데 사용됩니다. SortedDictionary는 내부적으로 이진 탐색 트리를 기반으로 동작하며, 요소가 추가되면 키를 기준으로 정렬된 상태가 항상 자동으로 유지됩니다.

구문(Syntax)

Add() 메서드의 기본 구문은 다음과 같습니다.

public void Add (TKey key, TValue val);

key: 컬렉션에 추가할 요소의 고유한 키입니다.
val: 해당 키와 함께 저장할 값입니다.

주요 특징 및 주의사항

  • 추가하려는 키가 이미 컬렉션에 존재하면 ArgumentException이 발생합니다.
  • 키가 null인 경우 ArgumentNullException이 발생합니다.
  • 삽입 작업의 시간 복잡도는 O(log n)입니다.
  • 중복 키로 인한 예외를 피하려면 Add() 호출 전에 ContainsKey() 메서드로 키 존재 여부를 먼저 확인하는 것이 안전합니다.

예제 1: 정수 키와 문자열 값 추가하기

다음은 int 형식의 키와 string 형식의 값을 가지는 SortedDictionary에 요소를 추가하는 예제입니다.

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(100, "Mobile");
      sortedDict.Add(200, "Laptop");
      sortedDict.Add(300, "Desktop");
      sortedDict.Add(400, "Speakers");
      sortedDict.Add(500, "Headphone");
      sortedDict.Add(600, "Earphone");

      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
      Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
   }
}

위 프로그램을 실행하면 아래와 같은 결과가 출력됩니다. 요소를 추가한 순서와 관계없이 키를 기준으로 오름차순 정렬되어 있는 것을 확인할 수 있습니다.

SortedDictionary key-value pairs...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone

예제 2: 문자열 키 사용 및 ContainsKey()와 함께 활용하기

이번에는 string 형식의 키와 값을 사용하고, 마지막에 ContainsKey() 메서드로 특정 키의 존재 여부를 확인하는 예제입니다.

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo {
   public static void Main(){
      SortedDictionary<string, string> sortedDict = new SortedDictionary<string, string>();
      sortedDict.Add("A", "John");
      sortedDict.Add("B", "Andy");
      sortedDict.Add("C", "Tim");
      sortedDict.Add("D", "Ryan");
      sortedDict.Add("E", "Kevin");
      sortedDict.Add("F", "Katie");
      sortedDict.Add("G", "Brad");

      Console.WriteLine("SortedDictionary key-value pairs...");
      IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
      while (demoEnum.MoveNext())
      Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);

      Console.WriteLine("\nThe SortedDictionary has the key F? = "+sortedDict.ContainsKey("F"));
   }
}

실행 결과는 다음과 같습니다. 마지막 줄에서 ContainsKey() 메서드를 통해 키 "F"가 컬렉션에 존재함을 확인할 수 있습니다. 이처럼 Add()를 호출하기 전에 ContainsKey()로 키를 먼저 검사하면 중복 키로 인한 ArgumentException 발생을 사전에 방지할 수 있습니다.

SortedDictionary key-value pairs...
Key = A, Value = John
Key = B, Value = Andy
Key = C, Value = Tim
Key = D, Value = Ryan
Key = E, Value = Kevin
Key = F, Value = Katie
Key = G, Value = Brad
The SortedDictionary has the key F? = True

마무리

SortedDictionary.Add() 메서드는 데이터를 키 기준으로 항상 정렬된 상태로 저장해야 할 때 유용하게 사용됩니다. 다만 중복 키 추가 시 예외가 발생하고 null 키는 허용되지 않는다는 점에만 주의하면 됩니다. 조회 시 키 순서가 보장되어야 하는 상황이라면 일반 Dictionary보다 SortedDictionary가 더 적합한 선택입니다.