본문 바로가기
Languages/C#

C# Dictionary(사전 구조)

by 반도체는 프로그래밍을 좋아해 2023. 4. 11.
728x90

C#에서 Dictionary는 키(Key)와 값(Value)의 쌍으로 이루어진 데이터를 저장하는 자료구조 중 하나입니다. Dictionary 클래스는 System.Collections.Generic 네임스페이스에 속하며, 제네릭 타입을 사용하여 타입 안정성을 보장합니다.

Dictionary는 특정 키(Key)에 대응하는 값(Value)을 빠르게 검색할 수 있어 매우 유용합니다. 또한, 중복된 키를 허용하지 않으며, 키와 값은 모두 null이 될 수 없습니다.

아래는 Dictionary의 예시 코드입니다.

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Dictionary 인스턴스 생성
        Dictionary<string, int> ages = new Dictionary<string, int>();

        // 값 추가하기
        ages.Add("John", 25);
        ages.Add("Alice", 30);
        ages.Add("Bob", 20);

        // 값 검색하기
        int johnAge = ages["John"];
        bool hasAlice = ages.ContainsKey("Alice");

        // 값 삭제하기
        ages.Remove("Bob");

        // 값 출력하기
        foreach (KeyValuePair<string, int> entry in ages)
        {
            Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
        }
    }
}

위 코드에서는 Dictionary<string, int> 타입의 인스턴스를 생성하고, Add 메서드를 사용하여 값(Key-Value Pair)을 추가하고, [] 연산자를 이용하여 값을 검색합니다. 또한, ContainsKey 메서드를 사용하여 Dictionary에 해당 키가 있는지 검사하고, Remove 메서드를 사용하여 값을 삭제합니다. 마지막으로 foreach 루프를 사용하여 Dictionary의 모든 값을 출력합니다.

Dictionary<type, type>이다 보니 원하는 key, value type을 설정해서 추가할 수 있습니다.

Add 함수 또한 원하는 Type을 이용해서 key, value에 맞게 넣으면 추가 가능합니다.

foreach문에서도 같은 형식으로 지정한 key, value와 맞는 type을 이용해서 넣어주면 key,value를 뽑아 낼 수 있습니다.

만약 key나 value만 뽑고 싶다면 type key in ages.keys 나 type value in ages.values 를 사용하면 됩니다.

728x90