Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# 페어 클래스: KeyValuePair로 키-값 쌍 저장하기

C#에는 이름 그대로의 'Pair' 클래스는 존재하지 않지만, 두 개의 값을 하나의 단위로 묶어 저장할 수 있는 KeyValuePair<TKey, TValue> 구조체가 바로 페어 클래스 역할을 합니다. KeyValuePair를 List와 함께 사용하면 하나의 리스트 안에 여러 개의 키-값 쌍을 간편하게 저장하고 관리할 수 있습니다.

KeyValuePair 리스트 선언하기

먼저 KeyValuePair 타입의 리스트를 선언합니다. 아래 코드는 문자열 키(string)와 정수 값(int)으로 구성된 쌍을 담는 리스트입니다.

var myList = new List<KeyValuePair<string, int>>();

리스트에 요소 추가하기

Add() 메서드를 사용해 새로운 키-값 쌍을 추가할 수 있습니다.

myList.Add(new KeyValuePair<string, int>("Laptop", 1));
myList.Add(new KeyValuePair<string, int>("Desktop System", 2));
myList.Add(new KeyValuePair<string, int>("Tablet", 3));
myList.Add(new KeyValuePair<string, int>("Mobile", 4));
myList.Add(new KeyValuePair<string, int>("E-Book Reader", 5));
myList.Add(new KeyValuePair<string, int>("LED", 6));

전체 예제 코드

지금까지의 내용을 하나의 프로그램으로 작성하면 다음과 같습니다. foreach 반복문을 사용해 리스트에 저장된 모든 KeyValuePair를 순서대로 출력합니다.

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", 1));
        myList.Add(new KeyValuePair<string, int>("Desktop System", 2));
        myList.Add(new KeyValuePair<string, int>("Tablet", 3));
        myList.Add(new KeyValuePair<string, int>("Mobile", 4));
        myList.Add(new KeyValuePair<string, int>("E-Book Reader", 5));
        myList.Add(new KeyValuePair<string, int>("LED", 6));

        foreach (var val in myList) {
            Console.WriteLine(val);
        }
    }
}

실행 결과

[Laptop, 1]
[Desktop System, 2]
[Tablet, 3]
[Mobile, 4]
[E-Book Reader, 5]
[LED, 6]

Key와 Value 속성 활용하기

KeyValuePair 객체는 KeyValue 속성을 제공하므로, 필요에 따라 키나 값만 따로 조회할 수도 있습니다.

foreach (var val in myList) {
    Console.WriteLine($"키: {val.Key}, 값: {val.Value}");
}

이처럼 KeyValuePair는 Dictionary 컬렉션 없이도 간단한 키-값 형태의 데이터 목록을 만들고 관리할 때 매우 유용하게 활용할 수 있습니다.