[C# 문법] C# Dictionary 변환

소개

  • 오늘은 C# 에서 딕셔너리에 대해서 알아 보려고 합니다.
  • 앞선 포스팅에서 딕셔너리 기본적인 사용 방법에 대해서 알아 보았습니다.
  • 이번 포스터 부터는 조금 더 딕셔너리를 깊게 다뤄보려고 합니다.
  • 그중에서, 오늘은 다른 컬렉션을 딕셔너리로 변환하는 방법에 대해서 알려 드리도록 하겠습니다.

예제 코드

  • LINQ에 있는 ToDictionary 메서드를 사용하면 배열이나 리스트 컬렉션을 손쉽게 딕셔너리로 변환할 수 있습니다.
  • 딕셔너리로 변환하면 키를 지정해서 해당 값에 빠르게 접근할 수 있다는 장점이 있습니다.
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp7
{
    static class Program
    {
        static void Main(string[] args)
        {
            var list = InitialStudent();
            Type listType = Type.GetType(list.ToString());
            Console.WriteLine($"{listType}");

            // List 형태를 Dictionary 형태로 변환
            var dic = list.ToDictionary(stu => stu.Name);
            Type dicType = Type.GetType(dic.ToString());
            Console.WriteLine($"{dicType}");

            Console.WriteLine();

            // 딕셔너리 출력
            foreach (var student in dic)
            {
                Console.WriteLine($"Name : {student.Value.Name} Age : {student.Value.Age} Grade : {student.Value.Grade} Score : {student.Value.Score}");
            }
        }

        static List<Student> InitialStudent()
        {
            List<Student> list = new List<Student>()
            {
                new Student() { Name = "범범조조", Age = 20, Grade = "A", Score = 100 },
                new Student() { Name = "유재석", Age = 21, Grade = "B", Score = 10 },
                new Student() { Name = "김종국", Age = 22, Grade = "C", Score = 89 },
                new Student() { Name = "송지효", Age = 20, Grade = "D", Score = 60 },
                new Student() { Name = "하하", Age = 20, Grade = "A+", Score = 20 },
                new Student() { Name = "지석진", Age = 40, Grade = "F", Score = 55 },
                new Student() { Name = "아이유", Age = 30, Grade = "A", Score = 64 },
                new Student() { Name = "정형돈", Age = 22, Grade = "A", Score = 79 },
                new Student() { Name = "김성주", Age = 20, Grade = "A", Score = 29 }
            };

            return list;
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public int Score { get; set; }
    }
}

실행 결과

System.Collections.Generic.List`1[ConsoleApp7.Student]
System.Collections.Generic.Dictionary`2[System.String,ConsoleApp7.Student]

Name : 범범조조 Age : 20 Grade : A Score : 100
Name : 유재석 Age : 21 Grade : B Score : 10
Name : 김종국 Age : 22 Grade : C Score : 89
Name : 송지효 Age : 20 Grade : D Score : 60
Name : 하하 Age : 20 Grade : A+ Score : 20
Name : 지석진 Age : 40 Grade : F Score : 55
Name : 아이유 Age : 30 Grade : A Score : 64
Name : 정형돈 Age : 22 Grade : A Score : 79
Name : 김성주 Age : 20 Grade : A Score : 29
  • 위와 같이 Type이 list 에서 Dictionary 로 변환되어 출력된 것을 확인할 수 있습니다.
  • Linq를 이용하면 쉽게 Dictionary로 변환할 수 있습니다.
728x90

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

[C# 문법] C# 폴더 시간 비교하기  (0) 2021.09.02
[C# 문법] C# yield  (0) 2021.09.01
[C# 문법] Dictionary 다루기  (0) 2021.08.30
[C# 문법] C# LINQ Concat 메서드  (0) 2021.08.28
[C# 문법] C# LINQ Take, TakeWhile 메서드  (0) 2021.08.28

이 글을 공유하기

댓글

Designed by JB FACTORY