[C# 문법] Dictionary 다루기

소개

  • 오늘은 C# 에서 기본으로 제공해주는 컬렉션 중 하나인 Dictionary 컬렉션 다루는 방법에 대해서 알려 드리려고 합니다.
  • Dictionary는 Key, Value 로 이루어진 제네릭 클래스 입니다.
  • 오늘은 Dictionary 기본적으로 어떻게 요소를 추가하고, 꺼내고 다루는지에 대한 기본적인 방법에 대해서 알려 드리도록 하겠습니다.

Dictionary 초기화

using System.Collections.Generic;

namespace ConsoleApp7
{
    static class Program
    {
        static void Main(string[] args)
        {
            var dic = new Dictionary<int, Student>()
            {
                {1, new Student { Name = "범범조조", Age = 29, Grade = "A", Score = 100 } },
                {2, new Student { Name = "아이유", Age = 19, Grade = "F", Score = 90 } },
                {3, new Student { Name = "정형돈", Age = 49, Grade = "D", Score = 80 } },
                {4, new Student { Name = "박명수", Age = 29, Grade = "C", Score = 70 } },
                {5, new Student { Name = "하하", Age = 25, Grade = "B", Score = 75 } }
            };
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public int Score { get; set; }
    }
}
  • 위와 같이 Dictionary를 사용자 정의형으로 객체를 값으로 저장할 수 있습니다.

Dictionary 추가

using System.Collections.Generic;

namespace ConsoleApp7
{
    static class Program
    {
        static void Main(string[] args)
        {
            var dic = new Dictionary<int, Student>()
            {
                {1, new Student { Name = "범범조조", Age = 29, Grade = "A", Score = 100 } },
                {2, new Student { Name = "아이유", Age = 19, Grade = "F", Score = 90 } },
                {3, new Student { Name = "정형돈", Age = 49, Grade = "D", Score = 80 } },
                {4, new Student { Name = "박명수", Age = 29, Grade = "C", Score = 70 } },
                {5, new Student { Name = "하하", Age = 25, Grade = "B", Score = 75 } }
            };

            //Dictionary 추가
            dic.Add(6, new Student { Name = "KCM", Age = 40, Score = 60, Grade = "B" });
            dic.Add(7, new Student { Name = "김대명", Age = 40, Score = 60, Grade = "B+" });
            dic.Add(8, new Student { Name = "조정석", Age = 40, Score = 60, Grade = "C-" });
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public int Score { get; set; }
    }
}
  • Add 메서드를 사용해서 Dictionary 에서 요소를 추가할 수 있습니다.
  • Add 메서드는 Dictionary에 이미 키가 존재할 경우에 ArgumentException 예외를 발생시키므로 주의해야 합니다.

Dictionary 요소 꺼내기

using System;
using System.Collections.Generic;

namespace ConsoleApp7
{
    static class Program
    {
        static void Main(string[] args)
        {
            var dic = new Dictionary<int, Student>()
            {
                {1, new Student { Name = "범범조조", Age = 29, Grade = "A", Score = 100 } },
                {2, new Student { Name = "아이유", Age = 19, Grade = "F", Score = 90 } },
                {3, new Student { Name = "정형돈", Age = 49, Grade = "D", Score = 80 } },
                {4, new Student { Name = "박명수", Age = 29, Grade = "C", Score = 70 } },
                {5, new Student { Name = "하하", Age = 25, Grade = "B", Score = 75 } }
            };

            // Dictionary 요소 꺼내기
            Student stu = dic[1];
            Console.WriteLine($"{stu.Name} {stu.Age} {stu.Grade} {stu.Score}");
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public int Score { get; set; }
    }
}
  • Dictionary 요소를 꺼낼 떄도 배열에서 하는 방법과 거의 동일합니다.
  • [] 안에 인덱스 대신 키를 지정해서 키에 대응하는 값을 구할 수 있습니다.

Dictionary 요소 삭제

using System;
using System.Collections.Generic;

namespace ConsoleApp7
{
    static class Program
    {
        static void Main(string[] args)
        {
            var dic = new Dictionary<int, Student>()
            {
                {1, new Student { Name = "범범조조", Age = 29, Grade = "A", Score = 100 } },
                {2, new Student { Name = "아이유", Age = 19, Grade = "F", Score = 90 } },
                {3, new Student { Name = "정형돈", Age = 49, Grade = "D", Score = 80 } },
                {4, new Student { Name = "박명수", Age = 29, Grade = "C", Score = 70 } },
                {5, new Student { Name = "하하", Age = 25, Grade = "B", Score = 75 } }
            };

            // Dictionary 요소 삭제
            var result = dic.Remove(2);

            foreach (var item in dic.Values)
            {
                Console.WriteLine($"{item.Name}");
            }
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public int Score { get; set; }
    }
}
  • 위와 같이 Remove 메서드를 통해서 Dictionary 요소를 삭제할 수 있습니다.

Dictionary 전체 요소 꺼내기

using System;
using System.Collections.Generic;

namespace ConsoleApp7
{
    static class Program
    {
        static void Main(string[] args)
        {
            var dic = new Dictionary<int, Student>()
            {
                {1, new Student { Name = "범범조조", Age = 29, Grade = "A", Score = 100 } },
                {2, new Student { Name = "아이유", Age = 19, Grade = "F", Score = 90 } },
                {3, new Student { Name = "정형돈", Age = 49, Grade = "D", Score = 80 } },
                {4, new Student { Name = "박명수", Age = 29, Grade = "C", Score = 70 } },
                {5, new Student { Name = "하하", Age = 25, Grade = "B", Score = 75 } }
            };

            // Dictionary 전체 요소 꺼내기
            foreach (KeyValuePair<int, Student> item in dic)
            {
                Console.WriteLine($"Key : {item.Key} Value : {item.Value.Name}");
            }

            foreach (var item in dic)
            {
                Console.WriteLine($"Key : {item.Key} Value : {item.Value.Name}");
            }
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public int Score { get; set; }
    }
}
  • 배열이나 리스트와 마찬가지로 foreach 문을 통해서 Dictionary에 저장되어 있는 요소를 모두 가져올 수 있습니다.
728x90

'C# > C# 문법' 카테고리의 다른 글

[C# 문법] C# yield  (0) 2021.09.01
[C# 문법] C# Dictionary 변환  (0) 2021.08.30
[C# 문법] C# LINQ Concat 메서드  (0) 2021.08.28
[C# 문법] C# LINQ Take, TakeWhile 메서드  (0) 2021.08.28
[C# 문법] C# LINQ 형변환 OfType<T> 메서드  (0) 2021.08.25

이 글을 공유하기

댓글

Designed by JB FACTORY