본문 바로가기
C#/문법

[C#] Dictionary<TKey, TValue> 클래스

by luk_hwkim 2022. 5. 14.

개념

Dictionary는 Key인덱스와 Value를 세트로 가지는 연관배열 자료형이다.

Key와 Value를 세트로 다루는 배열을 연관배열이라고 하는데 C#에서는 Dictionary가 연관배열을 다루기 위한 클래스로 제공된다.

C++에서의 map, unordered_map과 비슷한 기능을 하는 자료형 클래스라고 볼 수 있을 것 같다.

 

사용

선언

Dictionary<Key타입, Value타입> 변수명 = new Dictionary<Key타입, Value타입>();

using System;
using System.Collections.Generic;
 
namespace csharp_practice
{
    public class practice
    {
        public static void main(string[] args)
        {
            Dictionary<string, string> dicEx = new Dictionary<string, string>();
 
            dicEx.Add("key1", "value1");
            dicEx.Add("key2", "value2");
            dicEx.Add("key3", "value3");
        }
    }
}

값 추가

Dictionary.Add(TKey, TValue)메서드를 사용하여 값을 추가

using System;
using System.Collections.Generic;
 
namespace csharp_practice
{
    public class practice
    {
        public static void main(string[] args)
        {
            Dictionary<string, string> dicEx = new Dictionary<string, string>()
            {
                {"key1", "value1" },
                {"key2", "value2" },
                {"key3", "value3" }
            };
        }
    }
}

컬렉션 이니셜라이저를 사용한 초기화 선언도 가능하다

using System;
using System.Collections.Generic;
 
namespace csharp_practice
{
    public class practice
    {
        public static void main(string[] args)
        {
            Dictionary<string, string> dicEx = new Dictionary<string, string>()
            {
                {"key1", "value1" },
                {"key2", "value2" },
                {"key3", "value3" }
            };
 
            if(false == dicEx.ContainsKey("key1"))
            {
                dicEx.Add("key1", "value1");
            }
        }
    }
}

데이터 존재 유무 확인

Dictionary.ContainsKey(TKey) 를 사용하여 데이터 존재 유무를 알 수 있다
true => 해당 key 존재, false => 해당 key 존재X

using System;
using System.Collections.Generic;
 
namespace csharp_practice
{
    public class practice
    {
        public static void Main(string[] args)
        {
            Dictionary<string, string> dicEx = new Dictionary<string, string>()
            {
                {"key1", "value1" },
                {"key2", "value2" },
                {"key3", "value3" }
            };
 
            foreach(var element in dicEx)
            {
                Console.WriteLine("[{0}-{1}]", element.Key, element.Value);
            }
 
            foreach(string key in dicEx.Keys)
            {
                Console.WriteLine(key);
            }
 
            foreach(string value in dicEx.Values)
            {
                Console.WriteLine(value);
            }
        }
    }
}

foreach반복문을 통한 데이터 순회

Dictionary도 다른 컬렉션 또는 배열처럼 foreach반복문을 통한 데이터 순회가 가능하다
Dictionary.Keys와 Dictionary.Values로 나눠서 Key, Value별로 각각 순회 하는 것도 가능

using System;
using System.Collections.Generic;
 
namespace csharp_practice
{
    public class practice
    {
        public static void Main(string[] args)
        {
            Dictionary<string, string> localNums = new Dictionary<string, string>()
            {
                {"서울", "02" },  {"부산", "051" }, {"대구", "053" },
                {"인천", "032" }, {"광주", "062" }, {"대전", "042" },
                {"울산", "052" }, {"세종", "044" }, {"경기", "031" }, 
                {"강원", "033" }, {"충북", "043" }, {"충남", "041" }, 
                {"전북", "063" }, {"전남", "061" }, {"경북", "054" }, 
                {"경남", "055" }, {"제주", "064" }
            };
 
            foreach(var element in localNums)
            {
                Console.WriteLine("{0}({1})", element.Key, element.Value);
            }
        }
    }
}

예제

using System;
using System.Collections.Generic;
 
namespace csharp_practice
{
    public class practice
    {
        public static void Main(string[] args)
        {
            Dictionary<string, string> localNums = new Dictionary<string, string>()
            {
                {"서울", "02" },  {"부산", "051" }, {"대구", "053" },
                {"인천", "032" }, {"광주", "062" }, {"대전", "042" },
                {"울산", "052" }, {"세종", "044" }, {"경기", "031" }, 
                {"강원", "033" }, {"충북", "043" }, {"충남", "041" }, 
                {"전북", "063" }, {"전남", "061" }, {"경북", "054" }, 
                {"경남", "055" }, {"제주", "064" }
            };
 
            foreach(var element in localNums)
            {
                Console.WriteLine("{0}({1})", element.Key, element.Value);
            }
        }
    }
}

실행결과

댓글