C#에서 Dictionary.Keys 속성은 Dictionary<TKey, TValue> 컬렉션에 저장된 모든 키(Key)를 한 번에 가져오는 데 사용됩니다. 이 속성은 키 전체를 담고 있는 KeyCollection 타입의 읽기 전용 뷰를 반환하며, 반복문을 통해 각 키를 순회하거나 특정 키의 존재 여부를 확인하는 작업에 유용하게 활용됩니다.
문법(Syntax)
Dictionary.Keys 속성의 기본 문법은 다음과 같습니다.
public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get; }반환되는 KeyCollection은 원본 딕셔너리의 키에 대한 스냅샷이 아니라 실시간 뷰(view)이므로, 딕셔너리가 변경되면 해당 변경 사항이 컬렉션에도 그대로 반영된다는 점을 기억해 두면 좋습니다.
예제 1: 모든 키 조회하기
다음 예제는 Dictionary.Keys 속성을 사용해 딕셔너리에 저장된 모든 키를 출력하는 방법을 보여줍니다.
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("\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 Key/value pairs... Key = One, Value = Kagido Key = Two, Value = Ngidi Key = Three, Value = Devillers Key = Four, Value = Smith Key = Five, Value = Warner All the keys.. Key = One Key = Two Key = Three Key = Four Key = Five
예제 2: 값 수정 후 키 목록 확인하기
다음 예제는 특정 키에 연결된 값을 수정한 뒤, Keys 속성으로 전체 키 목록을 다시 확인하는 과정을 보여줍니다. 값이 변경되더라도 키 자체에는 영향을 주지 않는다는 점을 확인할 수 있습니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<string, string> dict =
new Dictionary<string, string>();
dict.Add("One", "Chris");
dict.Add("Two", "Steve");
dict.Add("Three", "Messi");
dict.Add("Four", "Ryan");
dict.Add("Five", "Nathan");
Console.WriteLine("Count of elements = "+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.WriteLine("Value for key three = "+dict["Three"]);
dict["Three"] = "Katie";
Console.WriteLine("Updated value associated with key Three...");
Console.WriteLine(dict["Three"]);
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 Key/value pairs... Key = One, Value = Chris Key = Two, Value = Steve Key = Three, Value = Messi Key = Four, Value = Ryan Key = Five, Value = Nathan Value for key three = Messi Updated value associated with key Three... Katie All the keys.. Key = One Key = Two Key = Three Key = Four Key = Five
정리
Dictionary.Keys 속성은 딕셔너리의 모든 키를 KeyCollection 형태로 반환하며, foreach 반복문과 함께 사용하면 전체 키를 손쉽게 순회할 수 있습니다. 또한 인덱서(dict["키"])를 통해 특정 키의 값을 조회하거나 수정할 수 있으며, 값이 변경되어도 키 목록은 그대로 유지됩니다. 키와 값 쌍을 함께 다루고 싶다면 KeyValuePair를 활용한 순회 방식도 함께 참고하시기 바랍니다.