티스토리 뷰

ChatGPT에게 Dictionary에 대해 물어보았다.

 

-------------------------------------------------

답변

 

유니티에서 C#의 Dictionary<TKey, TValue>는 데이터의 쌍을 저장하는 자료 구조입니다. 키와 값으로 이루어진 항목들을 저장하며, 키를 통해 값을 빠르게 검색할 수 있습니다. Dictionary는 해시 테이블을 기반으로 하여 높은 성능을 제공합니다.

다음은 Dictionary의 기본적인 사용법과 몇 가지 예제입니다.

using System.Collections.Generic;

 

사용 전에 using을 추가한다.

Dictionary 기본 사용법

Dictionary 선언 및 초기화

Dictionary<string, int> ageDictionary = new Dictionary<string, int>();

 

여기서 string은 키의 타입이고, int는 값의 타입입니다.

(직접 해보니 키 타입과 값 타입은 꼭 string과 int가 아니어도 됨.)

 

값 추가

ageDictionary.Add("Alice", 30);
ageDictionary.Add("Bob", 25);

 

Add 메서드는 키와 값을 쌍으로 추가합니다. 동일한 키를 다시 추가하면 예외가 발생합니다.

 

값 접근

int aliceAge = ageDictionary["Alice"];

 

키를 사용하여 값을 조회할 수 있습니다. 키가 존재하지 않으면 KeyNotFoundException이 발생합니다.

 

값 수정

ageDictionary["Alice"] = 31;

 

기존 키에 대한 값을 수정할 수 있습니다.

 

값 제거

ageDictionary.Remove("Bob");

 

특정 키를 가진 항목을 제거합니다.

 

값 존재 여부 확인

bool hasAlice = ageDictionary.ContainsKey("Alice");
bool hasAge30 = ageDictionary.ContainsValue(30);

 

ContainsKey는 특정 키가 존재하는지 확인하고, ContainsValue는 특정 값이 존재하는지 확인합니다.

 

Dictionary 순회

foreach (var pair in ageDictionary)
{
    Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
}

 

KeyValuePair<TKey, TValue> 구조체를 사용하여 키와 값을 순회할 수 있습니다.

 

예제 코드

다음은 Dictionary를 사용하여 학생들의 점수를 저장하고 관리하는 간단한 예제입니다.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        // Dictionary 선언 및 초기화
        Dictionary<string, int> studentScores = new Dictionary<string, int>();

        // 값 추가
        studentScores.Add("John", 85);
        studentScores.Add("Jane", 92);
        studentScores.Add("Paul", 78);

        // 값 접근
        Console.WriteLine("John's score: " + studentScores["John"]);

        // 값 수정
        studentScores["John"] = 90;
        Console.WriteLine("John's updated score: " + studentScores["John"]);

        // 값 제거
        studentScores.Remove("Paul");

        // Dictionary 순회
        foreach (var student in studentScores)
        {
            Console.WriteLine($"Student: {student.Key}, Score: {student.Value}");
        }

        // 키 존재 여부 확인
        if (studentScores.ContainsKey("Jane"))
        {
            Console.WriteLine("Jane's score is available.");
        }
    }
}

 

이 코드는 학생들의 점수를 관리하는 간단한 프로그램을 구현합니다. Dictionary의 기본적인 사용법을 이해하는 데 도움이 될 것입니다.

 

-------------------------------------------------

 

댓글