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

C# Dictionary에서 키/값 쌍의 개수 구하기 – Count 속성 사용법

C#의 Dictionary에 저장된 키/값 쌍의 개수를 확인하려면 Count 속성을 사용하면 됩니다. Count 속성은 Dictionary에 현재 포함된 요소(키/값 쌍)의 총 개수를 정수로 반환하며, 요소를 추가하거나 제거할 때마다 자동으로 갱신됩니다.

예제 1: 요소 개수 확인 후 Clear()로 초기화하기

다음 예제에서는 Dictionary에 요소를 5개 추가한 후 Count 속성으로 개수를 확인하고, ContainsValue() 메서드로 특정 값의 존재 여부를 검사한 뒤, Clear() 메서드로 모든 요소를 제거했을 때 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", "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("키 = {0}, 값 = {1}", res.Key, res.Value);
      }

      if (dict.ContainsValue("Angelina"))
         Console.WriteLine("값을 찾았습니다!");
      else
         Console.WriteLine("해당 값은 Dictionary에 없습니다!");

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

출력 결과

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

요소 개수 = 5
키/값 쌍 출력...
키 = One, 값 = Chris
키 = Two, 값 = Steve
키 = Three, 값 = Messi
키 = Four, 값 = Ryan
키 = Five, 값 = Nathan
해당 값은 Dictionary에 없습니다!
초기화 후 키/값 쌍 출력...
현재 요소 개수 = 0

코드 설명

  • dict.Count – Dictionary에 저장된 키/값 쌍의 개수를 반환합니다.
  • ContainsValue() – Dictionary에 지정한 값이 존재하는지 여부를 확인합니다.
  • Clear() – Dictionary의 모든 키/값 쌍을 제거합니다. 호출 이후 Count 값은 0이 됩니다.

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

이번에는 더 간단한 예제를 통해 Dictionary의 요소 개수를 확인하는 방법을 살펴보겠습니다.

using System;
using System.Collections.Generic;

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

      Console.WriteLine("요소 개수 = " + dict.Count);
   }
}

출력 결과

요소 개수 = 5

정리

Dictionary의 요소 개수를 확인할 때는 Count 속성을 사용하는 것이 가장 간단하고 효율적입니다. Count 속성은 O(1) 시간 복잡도로 동작하므로 Dictionary의 크기와 관계없이 항상 빠르게 개수를 얻을 수 있습니다.