C#의 사전은 키와 값의 모음입니다. System.Collection.Generics 네임스페이스의 일반 컬렉션 클래스입니다.
구문
다음은 구문입니다 -
public class Dictionary<TKey,TValue>
위에서 key 매개변수는 사전에 있는 키의 유형이고 TValue는 값의 유형입니다.
예
이제 사전을 만들고 몇 가지 요소를 추가해 보겠습니다. −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "John");
dict.Add("Two", "Tom");
dict.Add("Three", "Jacob");
dict.Add("Four", "Kevin");
dict.Add("Five", "Nathan");
Console.WriteLine("Key/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
}
} 출력
이것은 다음과 같은 출력을 생성합니다 -
Key/value pairs... Key = One, Value = John Key = Two, Value = Tom Key = Three, Value = Jacob Key = Four, Value = Kevin Key = Five, Value = Nathan
예
이제 예제를 보고 일부 키를 제거해 보겠습니다. −
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "Kagido");
dict.Add("Two", "Ngidi");
dict.Add("Three", "Devillers");
dict.Add("Four", "Smith");
dict.Add("Five", "Warner");
Console.WriteLine("Count of elements = "+dict.Count);
Console.WriteLine("Removing some keys...");
dict.Remove("Four");
dict.Remove("Five");
Console.WriteLine("Count of elements (updated) = "+dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<string, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.Write("\nAll the keys..\n");
Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
foreach(string str in allKeys){
Console.WriteLine("Key = {0}", str);
}
}
} 출력
이것은 다음과 같은 출력을 생성합니다 -
Count of elements = 5 Removing some keys... Count of elements (updated) = 3 Key/value pairs... Key = One, Value = Kagido Key = Two, Value = Ngidi Key = Three, Value = Devillers All the keys.. Key = One Key = Two Key = Three