C# 기초 공부

[C#] KeyValuePair vs Dictionary 차이점

jju_developer 2024. 10. 2. 21:40
728x90

안녕하세요~ jju_developer입니다.

KeyValuePair 이게 뭔지 아시는분 계신가요?

 

도통 저거는 정처기에서도 못본 컬렉션이라서 정리를 해보았습니다.

 

C#에서 KeyValuePair와 Dictionary는 데이터를 키-값 쌍(Key-Value Pair)으로 관리할 때

사용되는 중요한 컬렉션이라고 합니다.

 

Java의 HashMap과 유사한 개념으로, 데이터를 키를 통해 빠르게 조회할 수 있는 장점을 제공하죠.

 

 

KeyValuePair

1. 단일 키와 그에 대응하는 값을 저장하는 구조

using System;
using System.Collections.Generic;

namespace jju_developer
{
    class Program
    {
        static void Main(string[] args)
        {
            // KeyValuePair 선언 및 사용
            KeyValuePair<int, string> student = new KeyValuePair<int, string>(1, "jju");

            Console.WriteLine($"학생 ID: {student.Key}, 이름: {student.Value}");
        }
    }
}

위 코드에서는 학생의 ID와 이름을 키와 값으로 저장했습니다. 

KeyValuePair<int, string> 타입은 키로 int, 값으로 string을 사용합니다.

 

 

Dictionary

Dictionary는 여러 개의 위에서 본 키벨류페어를 모아놓은 것 입니다.

다시 말해, 저렇게 키, 값 이 많이 있는 자료구조죠.

 

1. 키는 유일하다.

2. 값은 중복이 가능하다.

3. 빠른 검색과 수정이 가능하다.

using System;
using System.Collections.Generic;

namespace jju_developer
{
    class Program
    {
        static void Main(string[] args)
        {
            // Dictionary 선언 및 초기화
            Dictionary<int, string> students = new Dictionary<int, string>();

            // 값 추가
            students.Add(1, "jju");
            students.Add(2, "youngHee");
            students.Add(3, "vicky");

            // 값 조회
            Console.WriteLine("ID 1: " + students[1]); // John 출력

            // 값 수정
            students[1] = "gj";
            Console.WriteLine("변경된 ID 1: " + students[1]); // gj 출력

            // 키-값 출력
            foreach (KeyValuePair<int, string> student in students)
            {
                Console.WriteLine($"학생 ID: {student.Key}, 이름: {student.Value}");
            }
        }
    }
}

 

 

 

KeyValuePair vs Dictionary 차이점

  • KeyValuePair는 단일 키-값 쌍을 저장하지만,
  • Dictionary는 여러 키-값 쌍을 관리하는 컬렉션입니다.
  • Dictionary는 Add(), Remove(), ContainsKey() 등 다양한 메서드를 제공하여 데이터 관리에 매우 유용합니다.
  • KeyValuePair는 읽기 전용의 성격이 강하며, 데이터를 한 번 설정하면 변경할 수 없습니다. 반면,
  • Dictionary는 키를 통해 값을 수정할 수 있습니다.

 

  • 자바의 HashMap과의 유사성
    자바의 HashMap은 C#의 Dictionary와 매우 유사합니다. 
  • 둘 다 키-값 쌍으로 데이터를 저장하고, 키를 이용해 빠르게 값을 검색하는 특징이 있습니다. 
  • Java에서도 HashMap.put()을 통해 데이터를 추가하고, get()으로 값을 가져올 수 있는데, 
  • C#의 Add()와 [] 접근 방식이 이에 대응됩니다.

차이점을 좀 아시겠나용?

 

Dictionary<string, string> openWith = new Dictionary<string, string>();

// Dictionary에 요소를 추가합니다. 
// 키는 중복되지 않지만, 값은 중복될 수 있습니다.
// 마치 KeyValuePair가 모여 있는 형태입니다~~~~
openWith.Add("txt", "notepad.exe"); // "txt" 파일을 notepad.exe로 연다는 의미
openWith.Add("bmp", "paint.exe");   // "bmp" 파일을 paint.exe로 연다는 의미
openWith.Add("dib", "paint.exe");   // "dib" 파일을 paint.exe로 연다는 의미 (값이 중복됨)
openWith.Add("rtf", "wordpad.exe"); // "rtf" 파일을 wordpad.exe로 연다는 의미

// Add 메서드는 키가 중복되면 예외를 발생시킵니다.
// "txt" 키가 이미 추가되어 있기 때문에 예외가 발생합니다.
try
{
    openWith.Add("txt", "winword.exe"); // 이미 "txt" 키가 존재하므로 예외 발생
}
catch (ArgumentException)
{
    // 예외가 발생하면 실행되는 코드입니다.
    // 이미 "txt"라는 키가 존재한다는 메시지를 출력합니다.
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}

 

KeyValuePair 는 단일 키, 쌍

Dictionary 는 KeyValuePair 가 여러개 모음집~

 

1. 참고 자료

 

KeyValuePair<TKey,TValue> 구조체 (System.Collections.Generic)

설정하거나 검색할 수 있는 키/값 쌍을 정의합니다.

learn.microsoft.com

 

2. 참고자료

 

 

Dictionary<TKey,TValue> 클래스 (System.Collections.Generic)

키 및 값의 컬렉션을 나타냅니다.

learn.microsoft.com

 

728x90