컴퓨터 언어/C#

[C#] C# 컬렉션 함수 Dictionary

훈츠 2020. 3. 3. 17:18
반응형

안녕하세요. 훈츠 입니다. 금일은 Dictionary 함수 사용법에 대해 알아보도록 하겠습니다. 

컬렉션 함수 딕셔네어리 (Dictionary)

  • 코틀린의 map 처럼 key, value 로 구성 되며, key값이 중복되면 안됩니다. 
  • ContainsKey("key"), TryGetValue("cat" , out test) 
  • KeyValuePair
    • Dictionary 컬렉션을 상속받기에 루프에서 사용할 땐 keyValuePair 구조체를 이용합니다.
  • keyNotFoundException 
    • 존재 하지 않는 키를 사용하면 에러를 발생합니다. 항상 Containkey나 TryGetValue로 키 존재 여부를 먼저 확인 해야 합니다.  

ContainsKey("key"), TryGetValue("cat" , out test) 

var dict = new Dictionary<int, String>();
dict.Add(1, "first");
dict.Add(2, "second");

//Containskey 
if (dict.ContainsKey(1))
{
	var show = dict[1];     //배열 형태로 불러 올수 있습니다. 
	Console.WriteLine(show);
}

//TryGetValue 형태 1      
string test;
if(dict.TryGetValue(1, out test))
{              
	Console.WriteLine(test);
}

//TryGetValue 형태 2      
if (dict.TryGetValue(1, out string descripion))
{
	Console.WriteLine("des " + descripion);
} 

출력 화면 

key 와 value 값을 get 하는 방법 입니다. 

var dict = new Dictionary<int, String>();
dict.Add(1, "first");
dict.Add(2, "second");

//get a list of all the keys
List<int> keys = new List<int>(dict.Keys);  		 //keys 값 가져오기
List<String> values = new List<String>(dict.Values); //values 값 가져오기

foreach (int key in keys)
{
	Console.WriteLine(key);
}

foreach (string value in values)
{
	Console.WriteLine("value " + value);
}

출력화면

pair 로 가져오는 방법 입니다. 

var dict = new Dictionary<int, String>();
dict.Add(1, "first");
dict.Add(2, "second");

foreach (var pair in dict)
{
	Console.WriteLine("key , value " + pair.Key + pair.Value);
}

출력 화면 

Pair 에 <String, List<String> 형태를 가져오는 법입니다. 

public static Dictionary<String, List<String>> CPUs = new Dictionary<String, List<String>>()
List<String> lists = new List<String> { " " };

foreach(var pair in CPUs)
{
	foreach(string value in pair.Value) { 
	list.Add(value);
	}
}

 

반응형