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

C# SortedDictionary에 특정 키가 포함되어 있는지 확인하는 방법

C#에서 SortedDictionary 컬렉션에 지정된 키가 포함되어 있는지 확인하려면 ContainsKey() 메서드를 사용합니다. 이 메서드는 해당 키가 사전에 존재하면 true를, 존재하지 않으면 false를 반환하는 불리언(Boolean) 값을 리턴합니다.

ContainsKey() 메서드는 정렬된 이진 탐색 트리 구조를 기반으로 동작하기 때문에 시간 복잡도가 O(log n)으로, 대용량 데이터에서도 매우 효율적으로 키를 검색할 수 있습니다.

예제 1: 정수형 키 확인

다음은 SortedDictionary에 키 200이 존재하는지 확인하는 예제입니다.

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo {
    public static void Main() {
        SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();
        sortedDict.Add(100, "Mobile");
        sortedDict.Add(200, "Laptop");
        sortedDict.Add(300, "Desktop");
        sortedDict.Add(400, "Speakers");
        sortedDict.Add(500, "Headphone");
        sortedDict.Add(600, "Earphone");

        Console.WriteLine("SortedDictionary key-value pairs...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);

        Console.WriteLine("\nThe SortedDictionary has the key 200? = " + sortedDict.ContainsKey(200));
    }
}

출력 결과

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

SortedDictionary key-value pairs...
Key = 100, Value = Mobile
Key = 200, Value = Laptop
Key = 300, Value = Desktop
Key = 400, Value = Speakers
Key = 500, Value = Headphone
Key = 600, Value = Earphone

The SortedDictionary has the key 200? = True

출력 결과에서 볼 수 있듯이 키 200이 SortedDictionary에 존재하므로 ContainsKey(200) 메서드는 True를 반환했습니다.

예제 2: 문자열 키 확인

이번에는 문자열 타입의 키를 사용하는 또 다른 예제를 살펴보겠습니다.

using System;
using System.Collections;
using System.Collections.Generic;

public class Demo {
    public static void Main() {
        SortedDictionary<string, string> sortedDict = new SortedDictionary<string, string>();
        sortedDict.Add("A", "John");
        sortedDict.Add("B", "Andy");
        sortedDict.Add("C", "Tim");
        sortedDict.Add("D", "Ryan");
        sortedDict.Add("E", "Kevin");
        sortedDict.Add("F", "Katie");
        sortedDict.Add("G", "Brad");

        Console.WriteLine("SortedDictionary key-value pairs...");
        IDictionaryEnumerator demoEnum = sortedDict.GetEnumerator();
        while (demoEnum.MoveNext())
            Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);

        Console.WriteLine("\nThe SortedDictionary has the key F? = " + sortedDict.ContainsKey("F"));
    }
}

출력 결과

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

SortedDictionary key-value pairs...
Key = A, Value = John
Key = B, Value = Andy
Key = C, Value = Tim
Key = D, Value = Ryan
Key = E, Value = Kevin
Key = F, Value = Katie
Key = G, Value = Brad

The SortedDictionary has the key F? = True

정리

SortedDictionary에서 특정 키의 존재 여부를 확인할 때는 ContainsKey() 메서드를 사용하는 것이 가장 간단하고 안전한 방법입니다. 만약 존재하지 않는 키에 인덱서([])로 접근하면 KeyNotFoundException이 발생할 수 있으므로, 값을 읽기 전에 반드시 ContainsKey()로 키의 존재 여부를 먼저 확인하는 것이 좋습니다.