Windows Application

[C#] Dictonary 간단하게 총 정리

CodeSlave 2023. 3. 15. 14:26

C#에서 Dictonary를 활용할 때 자주 사용하던 함수 등에 대해 설명합니다.

 

* Dictionary 클래스 사용 시

//Dictionary 클래스를 사용하기 위한 네임스페이스
using System.Collections.Genetric;

 

* Dictionary의 선언, 정의, 초기화

//선언과 정의
var tempDic = new Dictonary<string, string>();

//선언과 정의2
Dictionary<string, string> tempDic2 = new Dictionary<string, string>();

//선언과 정의, 초기화
var tempDic = new Dictonary<string, string>( 
	{ "key1", "value1" }, 
	{ "key2", "value2" },
	{ "key3", "value3" }
);

 

* Dictionary에 Add로 요소 추가/삭제

var tempDic = new Dictionary<string, string>();

//요소를 추가합니다.
tempDic.Add("key1", "value1");
tempDic.Add("key2", "value2");
tempDic.Add("key3", "value3");

//요소를 삭제합니다.
tempDic.Remove("key1");
tempDic.Remove("key2");
tempDic.Remove("key3");

 

* Dictionary의 Key값이 존재하는 지 검사

if(tempDic.ContainsKey("key1"))
{
	Console.WriteLine("키가 존재합니다.");
}
else
{
	Console.WriteLine("키가 없습니다.");
}

 

* Dictionary의 Key값으로 value값을 추출, 불러오기

//단순 추출, 키값이 없으면 에러(KeyNotFoundException) 발생
Console.WriteLine(tempDic["key1"]);

//안전하게 추출하기
string result = "";
if(tempDic.TryGetValue("key1", out string result))
{
	//키값이 존재할 때
	Console.WriteLine(result);
}
else
{
	//키값이 없을 때
	Console.WriteLine("키값이 없습니다");
}

 

* foreach문으로 모두 추출, 불러오기

//KEY값과 VALUE값 모두를 출력합니다.
foreach(KeyValuePair<string, string> dicItem in tempDic) {
	Console.WriteLine("key:{0}, value:{1}]", dicItem.Key, dicItem.Value);  
}

//VALUE값만 출력합니다.
foreach(string val in tempDic.Values) {
	Console.WriteLine(val);  
}

 

* Dictionary의 마지막 Key값, 마지막 Value를 추출, 불러오기

//마지막에 추가된 KEY값
Console.WriteLine(tempDic.Keys.Last());

//마지막에 추가된 KEY값
Console.WriteLine(tempDic.Values.Last());

 

* Dictionary의 가장 큰 Key값, 가장 큰 Value값을 추출, 불러오기

//가장 큰 Key값
Console.WriteLine(tempDic.Keys.Max());

//가장 큰 Value값
Console.WriteLine(tempDic.Values.Max());