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

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

C#의 Dictionary<TKey, TValue>.Add() 메서드는 사전(딕셔너리) 컬렉션에 지정된 키(key)와 값(value)의 쌍을 추가할 때 사용하는 메서드입니다. 키는 사전 내에서 반드시 고유해야 하며, 이미 존재하는 키를 다시 추가하려고 하면 ArgumentException 예외가 발생한다는 점에 유의해야 합니다.

문법(Syntax)

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

public void Add (TKey key, TValue val);

여기서 key 매개변수는 추가할 요소의 고유 키를, val 매개변수는 해당 키와 연결될 값을 의미합니다.

예제 1: 기본 사용법

다음 예제는 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("키/값 쌍 목록...");
        foreach(KeyValuePair<string, string> res in dict){
            Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
        }
    }
}

실행 결과

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

키/값 쌍 목록...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan

예제 2: Count 속성으로 요소 개수 확인하기

이번 예제에서는 Add() 메서드로 요소를 추가하기 전과 후의 사전 크기를 Count 속성으로 확인해 보겠습니다.

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("요소 개수 = " + dict.Count);

        dict.Add("Six", "Anne");
        dict.Add("Seven", "Katie");

        Console.WriteLine("요소 개수(추가 후) = " + dict.Count);
        Console.WriteLine("키/값 쌍 목록...");
        foreach(KeyValuePair<string, string> res in dict){
            Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
        }
    }
}

실행 결과

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

요소 개수 = 5
요소 개수(추가 후) = 7
키/값 쌍 목록...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Key = Six, Value = Anne
Key = Seven, Value = Katie

마무리 및 참고 사항

  • Add() 메서드는 새로운 키-값 쌍을 추가할 때만 사용됩니다. 기존 키의 값을 변경하려면 인덱서(dict[key] = value;)를 사용해야 합니다.
  • 키(key)에는 null을 사용할 수 없지만, 참조형인 값(value)이 null인 것은 허용됩니다.
  • 키의 존재 여부를 미리 확인하려면 ContainsKey() 또는 TryGetValue() 메서드를 함께 활용하는 것이 좋습니다.