[개발] C#, .Net

[C#] SortedDictionary 란?

  • -
반응형

SortedDictionary<TKey, TValue>는 C#의 컬렉션 중 하나로, 키-값 쌍을 저장하고 키를 기준으로 정렬된 순서로 데이터를 유지하는 사전(dictionary)입니다. .

 

NET의 System.Collections.Generic 네임스페이스에 속해 있습니다.

 

SortedDictionary는 이진 검색 트리(BST)를 기반으로 하며, 키가 항상 오름차순으로 정렬됩니다.

 

 

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // SortedDictionary 선언 및 초기화
        SortedDictionary<int, string> sortedDict = new SortedDictionary<int, string>();

        // 항목 추가
        sortedDict.Add(3, "Three");
        sortedDict.Add(1, "One");
        sortedDict.Add(2, "Two");
        sortedDict.Add(4, "Four");

        // 값 출력 (키 기준 정렬됨)
        Console.WriteLine("SortedDictionary 내용:");
        foreach (KeyValuePair<int, string> kvp in sortedDict)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }

        // 특정 키의 값에 접근
        Console.WriteLine("\nKey 2의 값: " + sortedDict[2]);

        // 키의 존재 여부 확인
        if (sortedDict.ContainsKey(3))
        {
            Console.WriteLine("Key 3이 존재합니다.");
        }

        // 값의 존재 여부 확인
        if (sortedDict.ContainsValue("Four"))
        {
            Console.WriteLine("Value 'Four'가 존재합니다.");
        }

        // 항목 삭제
        sortedDict.Remove(1);
        Console.WriteLine("\nKey 1이 삭제된 후의 SortedDictionary 내용:");
        foreach (KeyValuePair<int, string> kvp in sortedDict)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }

        // TryGetValue 메서드 사용
        if (sortedDict.TryGetValue(4, out string value))
        {
            Console.WriteLine("\nKey 4의 값: " + value);
        }

        // Count 프로퍼티 사용
        Console.WriteLine("\nSortedDictionary의 항목 수: " + sortedDict.Count);
    }
}
반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.