C#

[C#]Dictionary 초기화 방법

DevStory 2022. 8. 20.

Dictionary 초기화 방법

이번 포스팅은 C#의 Dictionary 객체를 초기화하는 몇 가지 방법을 소개합니다.


방법 1. null(권장하지 않음)

Dictionary 객체를 null로 초기화할 수 있습니다.

 

null로 초기화하는 경우 Ditionary 클래스에서 제공하는 메서드를 사용할 수 없으므로 null로 초기화하는 방법은 권장하지 않습니다.

 

다음 예제는 null로 초기화된 Dictionary 객체에서 Dictionary 클래스에서 제공하는 Add() 메서드를 호출했을 때, 런타임 에러가 발생하는 것을 보여줍니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = null;
    dict.Add("둘리", 10);
  }
}

[에러 내용]


방법 2. 기본 생성자 함수

기본 생성자 함수인 new Dictionary<TKey, TValue>()를 사용하여 Dictioanry 객체를 초기화할 수 있습니다.

 

TKey는 Key의 타입이며, TValue는 Value의 타입입니다.

 

다음 예제는 Dictioanry 객체를 기본 생성자 함수로 초기화하며, Add() 메서드를 사용하여 데이터를 추가하고 데이터의 개수를 출력합니다.

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

    dict.Add("둘리", 10);

    Console.WriteLine("dict.Count: " + dict.Count);
  }
}

[실행 결과]

dict.Count: 1

방법 3. 데이터 할당

Add() 메서드를 사용하지 않고 Dictionary 객체를 초기화하면서 데이터를 할당하고 싶은 경우 중괄호를 사용하는 방법과 인덱스 이니셜라이저를 사용하는 방법이 있습니다.

 

먼저, 중괄호를 사용하여 Dinctionary 객체를 초기화하면서 데이터를 할당합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>()
    {
      {"둘리", 100 },
      {"또치", 200 },
      {"마이콜", 300 }
    };

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

[실행 결과]

Key: 둘리, Value: 100
Key: 또치, Value: 200
Key: 마이콜, Value: 300

다음 방법은 인덱스 이니셜라이즈를 사용합니다.

 

대괄호에는 Dictionary의 키를 할당합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>()
    {
      ["둘리"] = 100,
      ["또치"] = 200,
      ["마이콜"] = 300
    };

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

[실행 결과]

Key: 둘리, Value: 100
Key: 또치, Value: 200
Key: 마이콜, Value: 300

중괄호와 인덱스 이니셜라이즈 차이점

중괄호와 인덱스 이니셜라이즈는 Dictionary 객체를 초기화하면서 데이터를 할당한다는 점은 동일하지만, 한 가지 차이점이 존재합니다.

 

Dictionary 클래스는 <Key, Value> 형식으로 키(Key)는 중복될 수 없습니다.

 

중괄호를 사용하여 중복되는 키를 할당하는 경우 ArgumentException이 발생합니다.

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

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

[에러 내용]

하지만, 인덱스 이니셜라이즈 방법으로 중복되는 키를 할당하면 예외가 발생하지 않고 가장 마지막에 위치한 <Key, Value>가 할당됩니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>()
    {
      ["둘리"] = 100,
      ["둘리"] = 200,
      ["둘리"] = 300
    };

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

[실행 결과]

Key: 둘리, Value: 300

방법 4. 다른 Dictionary 객체를 생성자 함수에 전달

Dictioanry 생성자 함수는 오버로드된 다양한 버전이 존재합니다.

 

생성자 함수에 다른 Dictionary 객체를 전달하여 초기화할 수 있습니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> originDict = new Dictionary<string, int>()
    {
      {"둘리", 100},
      {"또치", 200},
      {"마이콜", 300}
    };

    Dictionary<string, int> newDict = new Dictionary<string, int>(originDict);

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

[실행 결과]

Key: 둘리, Value: 100
Key: 또치, Value: 200
Key: 마이콜, Value: 300

방법 5. 비교자 전달

Dictionary 생성자 함수에 비교자를 전달할 수 있습니다.

 

Dictonary의 키는 중복될 수 없지만, 키의 타입이 문자열인 경우 기본 비교자는 대소문자를 구분하므로 다음과 같이 데이터를 할당할 수 있습니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = new Dictionary<string, int>()
    {
      {"aa", 100},
      {"AA", 200}
    };

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

[실행 결과]

Key: aa, Value: 100
Key: AA, Value: 200

Dictionary의 키가 대소문자 구분 없이 할당되어야 하는 경우 대소문자를 구분하지 않는 StringComparer 클래스의 CurrentCultureIgnoreCase 프로퍼티를 전달합니다.

 

다음 예제는 문자열 비교자를 Dictionary 생성자 함수에 전달하며, 문자열 "aa"와 "AA"를 대소문자 구분하지 않고 비교하므로 ArgumentException이 발생합니다.

class Program
{
  static void Main(string[] args)
  {
    Dictionary<string, int> dict = 
        new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase)
    {
      { "aa", 100},
      { "AA", 200}
    };

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

[에러 내용]

반응형

댓글