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

C# Dictionary(딕셔너리) 클래스 완벽 가이드

C#의 Dictionary(딕셔너리)는 키(Key)와 값(Value)을 한 쌍으로 저장하는 컬렉션입니다. System.Collections.Generic 네임스페이스에 속한 제네릭 컬렉션 클래스로, 각 키는 고유해야 하며 키를 통해 해당 값에 빠르게 접근할 수 있다는 장점이 있습니다.

문법(Syntax)

Dictionary 클래스의 기본 선언 문법은 다음과 같습니다.

public class Dictionary<TKey,TValue>

여기서 TKey는 딕셔너리에 저장할 키의 데이터 타입을, TValue는 값의 데이터 타입을 의미합니다.

예제 1: Dictionary 생성 및 요소 추가

이제 Dictionary 객체를 생성하고 Add() 메서드로 요소를 추가한 뒤, foreach 문으로 전체 키-값 쌍을 출력해 보겠습니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict = new Dictionary<string, string>();
      dict.Add("One", "John");
      dict.Add("Two", "Tom");
      dict.Add("Three", "Jacob");
      dict.Add("Four", "Kevin");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Key/value pairs...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan

예제 2: 키 제거 및 전체 키 조회

다음 예제에서는 Remove() 메서드로 특정 키를 삭제하고, Count 속성으로 요소 개수 변화를 확인합니다. 또한 Keys 속성을 사용해 딕셔너리의 모든 키를 조회하는 방법도 살펴봅니다.

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict = new Dictionary<string, string>();
      dict.Add("One", "Kagido");
      dict.Add("Two", "Ngidi");
      dict.Add("Three", "Devillers");
      dict.Add("Four", "Smith");
      dict.Add("Five", "Warner");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("Removing some keys...");
      dict.Remove("Four");
      dict.Remove("Five");
      Console.WriteLine("Count of elements (updated) = "+dict.Count);
      Console.WriteLine("
Key/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.Write("
All the keys..
");
      Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
      foreach(string str in allKeys){
         Console.WriteLine("Key = {0}", str);
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Count of elements = 5
Removing some keys...
Count of elements (updated) = 3
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers
All the keys..
Key = One
Key = Two
Key = Three

정리

C#의 Dictionary 클래스는 다음과 같은 특징을 가집니다.

- 키의 고유성: 동일한 키를 중복해서 추가할 수 없습니다.
- 빠른 조회 속도: 해시 기반 구조로 키를 통해 값에 거의 O(1) 시간에 접근할 수 있습니다.
- 동적 관리: Add(), Remove() 등의 메서드로 요소를 자유롭게 추가·삭제할 수 있으며, Count 속성으로 현재 요소 수를 확인할 수 있습니다.
- 키/값 순회: KeyValuePair<TKey, TValue>와 함께 foreach 문을 사용하면 모든 항목을 손쉽게 순회할 수 있습니다.