C#에서 Dictionary<TKey, TValue> 클래스의 Values 속성은 딕셔너리에 저장된 모든 값을 한꺼번에 가져오는 데 사용됩니다. 이 속성은 키(key)는 제외하고 값(value)만 포함하는 ValueCollection 타입의 컬렉션을 반환하며, foreach 문과 함께 사용하면 딕셔너리의 모든 값을 손쉽게 순회할 수 있습니다.
구문
Dictionary.Values 속성의 구문은 다음과 같습니다.
public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection Values { get; }
이 속성은 읽기 전용(get 전용)이며, 호출 시점에 딕셔너리에 저장된 모든 값을 담은 컬렉션을 반환합니다.
예제 1 – 문자열 키를 가진 Dictionary
다음은 Dictionary.Values 속성을 활용해 딕셔너리의 모든 값을 출력하는 첫 번째 예제입니다.
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 values..\n");
Dictionary<string, string>.ValueCollection allValues = dict.Values;
foreach(string str in allValues){
Console.WriteLine("Value = {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 values.. Value = Kagido Value = Ngidi Value = Devillers Value = Smith Value = Warner
예제 2 – 정수 키를 가진 Dictionary
이번에는 키가 정수(int) 타입인 딕셔너리에서 Values 속성을 사용하는 예제를 살펴보겠습니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Kagido");
dict.Add(2, "Ngidi");
dict.Add(3, "Devillers");
Console.WriteLine("Count of elements = " + dict.Count);
Console.WriteLine("\nKey/value pairs...");
foreach(KeyValuePair<int, string> res in dict){
Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
}
Console.Write("\nAll the values..\n");
Dictionary<int, string>.ValueCollection allValues = dict.Values;
foreach(string str in allValues){
Console.WriteLine("Value = {0}", str);
}
}
}
실행 결과
위 코드를 실행하면 다음과 같은 출력이 생성됩니다.
Count of elements = 3 Key/value pairs... Key = 1, Value = Kagido Key = 2, Value = Ngidi Key = 3, Value = Devillers All the values.. Value = Kagido Value = Ngidi Value = Devillers
정리
Dictionary.Values 속성은 키가 아닌 값만 다루고 싶을 때 매우 유용합니다. 사용 시 알아두면 좋은 주요 특징은 다음과 같습니다.
- 읽기 전용: get 접근자만 제공되므로 Values 속성 자체에 값을 할당할 수 없습니다.
- 실시간 뷰(View): 반환된 ValueCollection은 원본 딕셔너리와 연동되어 있어, 딕셔너리 내용이 변경되면 그 변화가 그대로 반영됩니다.
- 순서 미보장: 값의 나열 순서는 정렬 순서가 아니므로, 특정 순서가 필요하다면 LINQ의 OrderBy 등으로 정렬한 후 사용하는 것이 좋습니다.