C# Dictionary 선언, 초기화, 삽입, 삭제, Contains, KeyValuePair

굥지·2024년 9월 24일
0

유니티 부트캠프

목록 보기
6/14

💡선언 방법

Dictionary<Key데이터형, Value데이터형> 딕셔너리명 = new Dictionary<Key데이터형, Value데이터형>()
Dictionary<string, string> cities = new Dictionary<string, string>();

💡초기화 방법

Dictionary<Key데이터형, Value데이터형> 딕셔너리명 = new Dictionary<Key데이터형, Value데이터형>(){
{Key, Value}, {Key, Value}, {Key, Value}, {Key, Value}
};

Dictionary<string, string> cities = new Dictionary<string, string>(){ {"한국", “서울” }, {"쿠바", “하바나”}, {"일본", “도쿄” }
};


💡삽입

딕셔너리명 .Add(Key, Value)
cities.Add("한국", "서울");

Key값 바꾸기

딕셔너리명[Key] = Value;
cities["한국"] = "부산";

💡삭제

딕셔너리명.Remove(삭제할 요소)
cities.Remove("한국");

💡검색

Dictionary에 해당요소를 갖고있는지 bool 리턴

리스트명.Contains(요소 이름)
cities.ContainsKey("미국")
결과 : true / false

Dictionary내의 모든 키와 값들을 출력

foreach(KeyValuePair<string, string>pair in cities)
{
Debug.Log(pair.Key + " : " + pair.Value);
}

💡길이

딕셔너리명.Count
cities.Count

💻코드

using UnityEngine;
using System.Collections.Generic;

public class Dic : MonoBehaviour
{
    void Start()
    {
        Dictionary<string, string> cities = new Dictionary<string, string>();

        cities.Add("한국", "서울");
        cities.Add("쿠바", "하바나");
        cities["한국"] = "부산";
        
        Debug.Log(cities.Count);
        if(!cities.ContainsKey("미국"))//bool값 리턴
        {
            Debug.Log("왜 미국은 없어요?");
        }

        foreach(string key in cities.Keys)
        {
            Debug.Log(cities[key]);
        }

        foreach(KeyValuePair<string, string>pair in cities)
        {
            Debug.Log(pair.Key + " : " + pair.Value);
        }
    }
}

🖨결과

0개의 댓글

관련 채용 정보