C#

[C#]Dictionary 데이터 추가하는 방법

DevStory 2022. 8. 20.

Dictionary 데이터 추가하는 방법

C#의 Dictionary 클래스는 <Key, Value> 형식의 데이터를 가지는 컬렉션입니다.

 

Dictionary에 데이터를 추가하는 방법을 살펴보기 전에 Dictionary의 특징을 이해할 필요가 있습니다.

- Dicitonary의 Key는 유니크하므로 중복될 수 없습니다.

- Dictionary의 Key는 null을 등록할 수 없습니다.

- Dictionary의 Value는 중복될 수 있습니다.

- Dictionary의 Value는 null을 등록할 수 있습니다.

 

이번 포스팅은 Dicitonary에 데이터를 추가할 수 있는 몇 가지 방법을 소개합니다.


방법 1. 초기화

첫 번째 방법으로 Dictioanry 객체를 선언할 때, 데이터를 추가할 수 있습니다.

 

이 방법은 C# 3.0부터 도입되어 되었으며, 배열처럼 데이터를 초기화할 수 있습니다.

 

다음 예제는 int 타입의 키와 string 타입의 값을 가지는 Dictionary 객체를 초기화합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<int, string> dict = new Dictionary<int, string>()
    {
      {1000, "둘리" },
      {2000, "또치" },
      {3000, "도우넛" }
    };

    foreach(KeyValuePair<int, string> item in dict)
    {       
      Console.WriteLine("Key: " + item.Key + ", Value: " + item.Value);
    }
  }
}

[실행 결과]

Key: 1000, Value: 둘리
Key: 2000, Value: 또치
Key: 3000, Value: 도우넛

동일한 키를 추가하는 경우 ArgumentException이 발생합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<int, string> dict = new Dictionary<int, string>()
    {
      {1000, "둘리" },
      {1000, "도우넛" }
    };

    foreach(KeyValuePair<int, string> item in dict)
    {
      Console.WriteLine("Key: " + item.Key + ", Value: " + item.Value);
    }
  }
}

[에러 내용]


방법 2. Dictionary의 Add 메서드

두 번째 방법으로 Dictionary 클래스에서 제공하는 Add() 메서드를 사용하여 데이터를 추가할 수 있습니다.

 

첫 번째 매개변수에 키를 전달하고 두 번째 매개변수에 값을 전달합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<int, string> dict = new Dictionary<int, string>();
    dict.Add(1000, "둘리");
    dict.Add(2000, "또치");
    dict.Add(3000, "도우넛");

    foreach (KeyValuePair<int, string> item in dict)
    {
      Console.WriteLine("Key: " + item.Key + ", Value: " + item.Value);
    }
  }
}

[실행 결과]

Key: 1000, Value: 둘리
Key: 2000, Value: 또치
Key: 3000, Value: 도우넛

Add() 메서드를 사용하여 동일한 키를 추가하는 경우 ArgumentException이 발생합니다.

 

다음 예제는 try-catch문을 사용하여 동일한 키를 추가하는 경우 예외 처리합니다.

class Program
{
  public static void AddItem<K, V>(Dictionary<K, V> dict, K key, V val)
  {
    try
    {
      dict.Add(key, val);
    } 
    catch (ArgumentException)
    {
      Console.WriteLine(key +"은(는) 이미 등록된 키(Key)입니다");
    }
  }

  static void Main(string[] args)
  {
    Dictionary<int, string> dict = new Dictionary<int, string>();
    AddItem(dict, 1000, "둘리");
    AddItem(dict, 1000, "도우넛");
    AddItem(dict, 2000, "마이콜");

    foreach (KeyValuePair<int, string> item in dict)
    {
      Console.WriteLine("Key: " + item.Key + ", Value: " + item.Value);
    }
  }
}

[실행 결과]

1000은(는) 이미 등록된 키(Key)입니다
Key: 1000, Value: 둘리
Key: 2000, Value: 마이콜

방법 3. Dictioanry의 TryAdd 메서드

마지막으로 Dictonary에 데이터가 추가된 경우 true를 반환하고 그렇지 않으면 false를 반환하는 TryAdd() 메서드를 사용할 수 있습니다.

 

TryAdd() 메서드의 특징은 동일한 키를 추가하는 경우 ArgumentException이 발생하지 않고 false를 반환합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<int, string> dict = new Dictionary<int, string>();

    Console.WriteLine("{Key: 1000, Value: \"둘리\"}가 Dictionary에 추가되었는가? " +
        dict.TryAdd(1000, "둘리"));

    Console.WriteLine("{Key: 1000, Value: \"도우넛\"}가 Dictionary에 추가되었는가? " +
        dict.TryAdd(1000, "도우넛"));

    Console.WriteLine("{Key: 2000, Value: \"마이콜\"}가 Dictionary에 추가되었는가? " +
        dict.TryAdd(2000, "마이콜"));

    Console.WriteLine("\ndict에 추가된 <Key, Value> 목록");
    foreach (KeyValuePair<int, string> item in dict)
    {
      Console.WriteLine("Key: " + item.Key + ", Value: " + item.Value);
    }
  }
}

[실행 결과]

{Key: 1000, Value: "둘리"}가 Dictionary에 추가되었는가? True
{Key: 1000, Value: "도우넛"}가 Dictionary에 추가되었는가? False
{Key: 2000, Value: "마이콜"}가 Dictionary에 추가되었는가? True

dict에 추가된 <Key, Value> 목록
Key: 1000, Value: 둘리
Key: 2000, Value: 마이콜
반응형

댓글