C# Dictionary 사용법

HK_An·2022년 5월 24일
1
post-thumbnail

들어가며

Java에 Map이 있다면 C#에서는 비슷한 자료형인 Dictionary가 있습니다.

기본적인 개념은 Java의 HashMap과 동일하게 Key와 Value로 이루어지며 사용 방법 또한 크게 다르지 않습니다.

예제코드

c#의 dictionary 사용은 아래와 같은 방법으로 할 수 있습니다.

// Dictionary 선언
Dictionary<string, string> myDictionary = new Dictionary<string, string>();

// 데이터 추가
myDictionary.Add("str1", "Hello");
myDictionary.Add("str2", " World!");

string str1 = null;
string str2 = null;

// 데이터 획득 방법 #1
str1 = myDictionary["str1"];
// 데이터 획득 방법 #2
myDictionary.TryGetValue("str2", out str2);

Java의 HashMap과의 차이점

Java와 다른 점은 데이터 획득 부분인데, dictionary ["원하는 키"]를 통하여 데이터에 접근이 가능하며
dictionary.TryGetValue("원하는 키", out 데이터 담을 변수)를 통해서도 데이터를 획득할 수 있습니다.

TryGetValue 메소드에 대해서 더 얘기를 하자면, 이 메소드는 기본적으로 해당 dictionary에서 입력받은 키를 찾아서 해당 키가 존재하는지 여부를 bool 타입으로 리턴합니다. 이를 이용하면 해당 dictionary에 원하는 키에 대한 유효성을 체크하여 유효할 때만 동작하는 로직을 간단하게 만들 수 있습니다.

if(myDictionary.TryGetValue("str2", out str2) {
	Console.WriteLine(str1 + str2);
}
else {
	Console.WriteLine("데이터가 존재하지 않습니다.");
}

0개의 댓글