본문 바로가기
C++ 200제/코딩 IT 정보

C# Dictionary 9가지 사용법, 딕셔너리 예제

by vicddory 2017. 7. 2.

Dictionary에 키값 4개를 추가한 뒤 비주얼 스튜디오 디버거를 통해 내용을 확인합니다. Dictionary는 키와 값을 쌍으로 보유합니다.

 

글 시작 전, 독학으로 공부하는 분들이 많으신데, 국비지원 무료 교육도 함께 알아보세요.

프로그래밍 공부 시작 단계에선 아무래도 혼자보단 여럿이 같이 배우는 게 낫습니다.

 

[▼ 국비지원 내일배움카드 신청하기 ]

 

내일배움카드 발급 자격 확인 및 신청 방법 가이드 - 1mm

내일배움카드 발급 자격과 신청방법에 대해 A to Z 상세하게 가이드로 알려드립니다.

kako.co.kr

 

string, int

다른 자료형을 요소로 사용합니다.

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
Dictionary<string, int> dictionary =
new Dictionary<string, int>();
 
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
}
}

Dictionary - string int
[C# 딕셔너리] 예제 소스

디버거를 통해 확인해 보면, key value 쌍들의 집합이 보입니다. 전형적인 KeyValuePair 구조체죠.

 

ContainsKey

주어진 문자열이 Dictionary에 존재하는 경우 true, 없으면 false가 리턴됩니다.

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
Dictionary<string, int> dictionary =
new Dictionary<string, int>();
 
dictionary.Add("apple", 1);
dictionary.Add("windows", 5);
 
// See whether Dictionary contains this string.
if (dictionary.ContainsKey("apple"))
{
int value = dictionary["apple"];
Console.WriteLine(value);
}
 
// See whether it contains this string.
if (!dictionary.ContainsKey("acorn"))
{
Console.WriteLine(false);
}
}
}

Dictionary - ContainsKey
[C# 딕셔너리] 예제 소스

TryGetValue

효율적인 검색 방법입니다. TryGetValue란 이름에서도 보이듯 키를 통해 값을 반환합니다.

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
Dictionary<string, string> values =
new Dictionary<string, string>();
 
values.Add("cat", "feline");
values.Add("dog", "canine");
// Use TryGetValue.
string test;
if (values.TryGetValue("cat", out test)) // Returns true.
{
Console.WriteLine(test); // This is the value at cat.
}
if (values.TryGetValue("bird", out test)) // Returns false.
{
Console.WriteLine(false); // Not reached.
}
}
}

Dictionary - TryGetValue
[C# 딕셔너리] 예제 소스

 

TryGetValue 사용 방법 2

이 함수 호출 시 out 키워드를 사용해도 위와 같은 효과를 낼 수 있습니다.

단, 비주얼 스튜디오 2017 이상에서 실행되는 코드입니다.

using System.Collections.Generic;
 
class Program
{
static void Main()
{
var values = new Dictionary<string, string>();
values.Add("A", "uppercase letter A");
values.Add("c", "lowercase letter C");
 
// Use inline "out string" with TryGetValue.
if (values.TryGetValue("c", out string description))
{
System.Console.WriteLine(description);
}
}
}

Dictionary - TryGetValue 2
[C# 딕셔너리] 예제 소스

KeyValuePair

IDictionary 컬렉션을 상속받기에 루프에서 사용할 땐 KeyValuePair 구조체를 이용합니다.

KeyNotFoundException

존재하지 않는 키를 사용하면 에러가 발생합니다. 항상 ContainsKey나 TryGetValue로 키 존재 여부를 먼저 확인합니다.

Loop. Dictionary의 자료 유형을 몰라도 콘솔로 확인할 수 있습니다. 아래 예제는 string 키와 int 값입니다.

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
// Example Dictionary again.
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"cat", 2},
{"dog", 1},
{"llama", 0},
{"iguana", -1}
};
 
// Loop over pairs with foreach.
foreach (KeyValuePair<string, int> pair in d)
{
Console.WriteLine(", ", pair.Key, pair.Value);
}
 
// Use var keyword to enumerate dictionary.
foreach (var pair in d)
{
Console.WriteLine(", ", pair.Key, pair.Value);
}
}
}

Dictionary - KeyValuePair
[C# 딕셔너리] 예제 소스

 

Var 키워드

위의 예제 마지막에선 var를 사용해 코드 양을 조금 줄였습니다. var를 이용하면 조금 수월합니다.

Key

키를 이용해 값을 조회하는 예제입니다. 이 방법은 당연히 느립니다. 예제용 소스입니다.

using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"cat", 2},
{"dog", 1},
{"llama", 0},
{"iguana", -1}
};
 
// Store keys in a List.
List<string> list = new List<string>(d.Keys);
 
// Loop through list.
foreach (string k in list)
{
Console.WriteLine(", ", k, d[k]);
}
}
}

Dictionary - KeyNotFoundException
[C# 딕셔너리] 예제 소스

Foreach 성능

루프에서 KeyValuePairs 방법과 키를 이용한 방법의 시간을 비교합니다.

using System;
using System.Collections.Generic;
using System.Diagnostics;
 
class Program
{
static void Main()
{
var test = new Dictionary<string, int>();
test["bird"] = 10;
test["frog"] = 20;
test["cat"] = 60;
 
int sum = 0;
const int _max = 1000000;
 
// Version 1: use foreach loop directly on Dictionary.
var s1 = Stopwatch.StartNew();
 
for (int i = 0; i < _max; i++)
{
foreach (var pair in test)
{
sum += pair.Value;
}
}
 
s1.Stop();
 
// Version 2: use foreach loop on Keys, then access values.
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
foreach (var key in test.Keys)
{
sum += test[key];
}
}
s2.Stop();
Console.WriteLine(s1.Elapsed.TotalMilliseconds);
Console.WriteLine(s2.Elapsed.TotalMilliseconds);
}
}

Dictionary - Var keyword
[C# 딕셔너리] 예제 소스

Sort

Dictionary를 직접 정렬할 순 없습니다. 키를 이용해 다른 컬렉션을 만들어 정렬할 순 있죠.

Type

Dictionary도 일반적인 클래스입니다. 사용하려면 키와 값의 자료형을 지정해야 합니다. 값은 어떤 유형이라도 허용합니다.

 
using System;
using System.Collections.Generic;
 
class Program
{
static void Main()
{
// Use a Dictionary with an int key.
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(100, "Bill");
dict.Add(200, "Steve");
 
// We can look up the int in the Dictionary.
if (dict.ContainsKey(200))
{
Console.WriteLine(true);
}
}
}

Dictionary - foreach
[C# 딕셔너리] 예제 소스

LINQ

Dictionary 확장 함수인 ToDictionary를 이용할 수 있습니다. ToDictionary는 System.Linq에서 제공합니다.

using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
static void Main()
{
string[] arr = new string[]
{
"One",
"Two"
};
 
var dict = arr.ToDictionary(item => item, item => true);
 
foreach (var pair in dict)
{
Console.WriteLine(", ",
pair.Key,
pair.Value);
}
}
}

Dictionary linq
[C# 딕셔너리] 예제 소스

 


프로그래밍 공부 시작 단계에선 아무래도 혼자보단 여럿이 같이 배우는 게 낫습니다.

 

[▼ 국비지원 내일배움카드 신청하기 ]

 

내일배움카드 발급 자격 확인 및 신청 방법 가이드 - 1mm

내일배움카드 발급 자격과 신청방법에 대해 A to Z 상세하게 가이드로 알려드립니다.

kako.co.kr

 

 

관련 글

댓글