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

C# Dictionary.Item[] 속성 완벽 정리 – 키로 값 조회하고 수정하기

C#에서 Dictionary<TKey, TValue>.Item[] 속성은 인덱서(indexer) 형태로 제공되며, 사전(Dictionary) 내에서 지정된 키(key)에 연결된 값을 가져오거나 설정할 때 사용됩니다. 이 속성 덕분에 배열처럼 대괄호([]) 안에 키를 넣어 간편하게 값에 접근할 수 있습니다.

구문

Dictionary.Item[] 속성의 기본 구문은 다음과 같습니다.

public TValue this[TKey key] { get; set; }

주요 특징

  • 값 읽기: dict[key] 형태로 지정한 키의 값을 반환합니다.
  • 값 쓰기: dict[key] = value 형태로 기존 키의 값을 수정하며, 키가 존재하지 않으면 새 항목이 추가됩니다.
  • 예외 발생: 값을 읽을 때 해당 키가 사전에 없으면 KeyNotFoundException이 발생합니다.

예제 1

다음은 Item[] 속성을 활용해 값을 조회하고 수정하는 전체 예제입니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      Dictionary<string, string> dict = new Dictionary<string, string>();
      dict.Add("One", "Chris");
      dict.Add("Two", "Steve");
      dict.Add("Three", "Messi");
      dict.Add("Four", "Ryan");
      dict.Add("Five", "Nathan");

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

      Console.WriteLine("키 Three의 값 = " + dict["Three"]);
      dict["Three"] = "Ronaldo";
      Console.Write("키 Three에 연결된 값이 수정되었습니다...");
      Console.WriteLine(dict["Three"]);

      if (dict.ContainsValue("Angelina"))
         Console.WriteLine("\n\n값을 찾았습니다!");
      else
         Console.WriteLine("\n\n사전에 해당 값이 없습니다!");

      dict.Clear();
      Console.WriteLine("비운 뒤 키/값 쌍...");
      foreach(KeyValuePair<string, string> res in dict) {
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.WriteLine("현재 요소 개수 = " + dict.Count);
   }
}

출력 결과

요소 개수 = 5
키/값 쌍 목록...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
키 Three의 값 = Messi
키 Three에 연결된 값이 수정되었습니다...Ronaldo
사전에 해당 값이 없습니다!
비운 뒤 키/값 쌍...
현재 요소 개수 = 0

코드 설명

먼저 5개의 키/값 쌍을 추가한 뒤, dict["Three"]를 통해 "Three" 키의 값을 읽어옵니다. 이후 dict["Three"] = "Ronaldo"처럼 인덱서에 값을 할당하면 해당 키의 값이 새로운 값으로 변경됩니다. 또한 ContainsValue() 메서드로 특정 값의 존재 여부를 확인했으며, Clear() 메서드 호출 후 Count가 0으로 줄어든 것도 확인할 수 있습니다.

예제 2

이번에는 Item[] 속성으로 값을 조회하고 갱신하는 과정만 간단히 살펴보겠습니다.

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      Dictionary<string, string> dict = new Dictionary<string, string>();
      dict.Add("One", "Chris");
      dict.Add("Two", "Steve");
      dict.Add("Three", "Messi");
      dict.Add("Four", "Ryan");
      dict.Add("Five", "Nathan");

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

      Console.WriteLine("키 Three의 값 = " + dict["Three"]);
      dict["Three"] = "Katie";
      Console.Write("키 Three에 연결된 값이 수정되었습니다...");
      Console.WriteLine(dict["Three"]);
   }
}

출력 결과

요소 개수 = 5
키/값 쌍 목록...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
키 Three의 값 = Messi
키 Three에 연결된 값이 수정되었습니다...Katie

정리

Dictionary.Item[] 속성(인덱서)은 C# 사전 컬렉션에서 가장 자주 사용되는 멤버 중 하나입니다. 키를 통해 값을 빠르게 읽고 쓸 수 있으며, 존재하지 않는 키에 값을 할당하면 새 항목이 추가된다는 점을 기억하면 됩니다. 반면, 존재하지 않는 키를 읽으려고 하면 KeyNotFoundException이 발생하므로, 필요하다면 TryGetValue()ContainsKey() 메서드를 함께 활용하는 것이 안전합니다.