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

C# Dictionary.Count 속성 사용법 – 키/값 쌍 개수 확인하기

C#의 Dictionary<TKey, TValue> 클래스에서 Count 속성은 딕셔너리에 현재 저장되어 있는 키/값 쌍(key/value pair)의 총 개수를 반환합니다. 이 속성은 읽기 전용이며, 내부적으로 요소 수를 별도로 관리하기 때문에 호출 시 O(1)의 시간 복잡도로 매우 빠르게 동작한다는 장점이 있습니다.

구문(Syntax)

public int Count { get; }

Countint 타입의 값을 반환하는 getter 전용(read-only) 속성입니다. 참고로 Capacity 속성은 내부 배열이 확보한 저장 공간의 크기를 의미하므로, 실제 요소 개수를 나타내는 Count와 값이 다를 수 있다는 점을 유의하세요.

예제 1 – Count 속성 기본 사용법

다음 예제는 요소 추가, 값 검색, 그리고 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("Key = {0}, Value = {1}", res.Key, res.Value);
        }

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

        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
해당 값은 딕셔너리에 없습니다!
초기화된 키/값 쌍...
현재 요소 개수 = 0

이 예제에서는 ContainsValue() 메서드를 사용하여 특정 값("Angelina")이 딕셔너리에 존재하는지 확인했습니다. 해당 값이 없으므로 조건 분기에 따라 안내 문구가 출력됩니다. 이후 Clear() 메서드로 모든 요소를 제거하자 Count 값이 5에서 0으로 바뀐 것을 확인할 수 있습니다.

예제 2 – 간단한 Count 조회

요소를 추가한 뒤 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", "David");
        dict.Add("Two", "Brian");
        dict.Add("Three", "Paul");
        dict.Add("Four", "Ryan");
        dict.Add("Five", "Nathan");

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

실행 결과

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

요소 개수 = 5

5개의 키/값 쌍을 추가한 후 Count 속성을 출력하면 정확히 5가 반환되는 것을 볼 수 있습니다.

핵심 정리

Dictionary.Count는 저장된 키/값 쌍의 실제 개수를 반환하는 읽기 전용 속성으로, 외부에서 값을 직접 설정할 수 없습니다. Clear() 메서드를 호출하면 모든 요소가 제거되어 Count가 0이 되며, 속성 조회 자체는 상수 시간(O(1))에 처리되므로 성능 걱정 없이 자유롭게 활용할 수 있습니다.