본문 바로가기
개발 기록/C#

[C#] Dictionary<T, T> 사용하기

by Ratataca 2021. 12. 9.

List 타입 활용하기

using System;
using System.Collections.Generic;

namespace realFinal {
    class Program {
        static void Main(string[] args) {

            List<int> numbers = new List<int>();
            List<int> initNumbers = new List<int>() {1, 2, 3, 4, 5, 6};

            numbers.Add(1);
            numbers.Add(3);
            numbers.Add(5);

            foreach(var i in numbers) { 
                Console.Write($"{i} ");       
            }

        }
    }
}



 

Dict 타입 활용하기

using System;
using System.Collections.Generic;

namespace realFinal {
    class Program {
        static void Main(string[] args) {

            IDictionary<string, string> data = new Dictionary<string, string>();
            var sameData = new Dictionary<string, string>();

            data.Add("apple", "사과");
            data.Add("banana", "바나나");
            data.Add("grape", "포도");

            data.Remove("apple");

            data["grape"] = "달달한 포도";

            try {
                data.Add("grape", "시큼한 포도");
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }


            foreach (var i in data) { 
                Console.Write("key : {0}\nvalue : {1} \n\n", i.Key, i.Value);       
            }

        }
    }
}

 


 

Dict과 TryGetValue() and ContainsKey() 매서드 활용하기

TryGetValue() : Dictionary에 같은 키가 존재할 때, 값을 가져오는 방법

            IDictionary<string, string> data = new Dictionary<string, string>();

            data.Add("apple", "사과");
            data.Add("banana", "바나나");
            data.Add("grape", "포도");

            if (data.TryGetValue("apple", out var output)){

                // 해당 키의 value가 output으로 들어감
                Console.WriteLine(output);
            }
            else {
                Console.WriteLine("키 없음");
            }

            foreach (var i in data) { 
                Console.Write("key : {0}\nvalue : {1} \n\n", i.Key, i.Value);       
            }

 

ContainsKey() : Dictionary에 같은 키가 존재하는지 확인 방법

            IDictionary<string, string> data = new Dictionary<string, string>();

            data.Add("apple", "사과");
            data.Add("banana", "바나나");
            data.Add("grape", "포도");

            if (!data.ContainsKey("json")) {
                data.Add("json", "test");
                Console.WriteLine(data["json"]);
            }


            // 필요에 따라 키 또는 값만 따로 뽑아 출력 가능
            var values = data.Values;

            foreach (var i in values) {
                Console.WriteLine(i);
            }

            // var keys = data.Keys;

 

ContainsValue() : Dictionary에 같은 값이 존재하는지 확인 방법

 

 

댓글