C#의 KeyValuePair는 키(Key)와 값(Value) 두 개의 데이터를 하나의 쌍으로 묶어 저장할 수 있는 제네릭 구조체입니다. 특히 List<KeyValuePair<TKey, TValue>> 형태로 사용하면 Dictionary처럼 키-값 데이터를 다루면서도 삽입 순서를 그대로 유지할 수 있다는 장점이 있습니다.
KeyValuePair 선언 및 요소 추가
먼저 KeyValuePair 타입의 리스트를 생성하고 요소를 추가하는 기본 코드입니다.
var myList = new List<KeyValuePair<string, int>>();
// 요소 추가
myList.Add(new KeyValuePair<string, int>("Laptop", 20));
myList.Add(new KeyValuePair<string, int>("Desktop", 40));
myList.Add(new KeyValuePair<string, int>("Tablet", 60));위 코드에서는 문자열 키와 정수 값으로 이루어진 KeyValuePair를 세 개 생성하여 리스트에 추가했습니다.
전체 예제 코드
다음은 KeyValuePair를 사용해 키와 값을 저장한 뒤, foreach 반복문으로 전체 항목을 출력하는 완전한 예제입니다.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var myList = new List<KeyValuePair<string, int>>();
// 요소 추가
myList.Add(new KeyValuePair<string, int>("Laptop", 20));
myList.Add(new KeyValuePair<string, int>("Desktop", 40));
myList.Add(new KeyValuePair<string, int>("Tablet", 60));
foreach (var val in myList) {
Console.WriteLine(val);
}
}
}실행 결과
[Laptop, 20] [Desktop, 40] [Tablet, 60]
Key와 Value 속성 개별 접근하기
KeyValuePair 객체는 Key와 Value 속성을 제공하므로, 필요에 따라 각각 따로 조회할 수도 있습니다.
foreach (var item in myList) {
Console.WriteLine($"키: {item.Key}, 값: {item.Value}");
}정리
KeyValuePair는 Dictionary 없이도 키-값 형태의 데이터를 List에 순서대로 관리할 수 있게 해주는 간편한 구조체입니다. 중복 키가 허용되어야 하거나, 항목의 삽입 순서가 중요한 경우에 특히 유용하게 활용할 수 있습니다.