[C# 문법] C# List를 DataTable로 변환하는 방법


 

안녕하세요.

 

오늘은 C# 문법에서 ToList 타입의 변수를 DataTable로 변환하는 방법에 대해서 알려드리려고 합니다.


제가 프로젝트를 하면서, DataTable에 저장되어 있는 값을 제가 다시 원하는 컬럼들만 가져와야 하는 경우가 있었습니다. 그래서 Linq 구문을 이용하여 Select new 구문을 통해 DataTable에 저장되어 있는 값들은 원하는 컬럼만 추려서 ToList 형태로 가져왔습니다.


그런데 문제가 생긴게 ToList로 가져온 변수를 다시 DataTable로 변환을 하고 싶었는데...도저히 방법을 몰라서 구글링을 하다가 해결 방법을 알게 되어서 같이 공유를 해 드리고자 포스팅을 하게 되었습니다.


 

이 구문은, 제가 직접 작성한 것이 아니라 구글링을 통해 알게되었습니다!


참고해 주세요~~

 

그럼 바로 예제코드를 통해 어떻게 ToListDataTable로 변환하는지 보여드리겠습니다.

 


예제 코드


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

using System.Reflection;

using System.Text;

using System.Threading.Tasks;

 

namespace test123

{

    class Program

    {

        static void Main(string[] args)

        {

            //  DataTable dt = new DataTable("Branches");  

            DataTable dt = new DataTable("Student");

            dt.Columns.Add("StudentId"typeof(Int32));

            dt.Columns.Add("StudentName"typeof(string));

            dt.Columns.Add("Address"typeof(string));

            dt.Columns.Add("MobileNo"typeof(string));

            //Data  

            dt.Rows.Add(1"Manish""Hyderabad""0000000000");

            dt.Rows.Add(2"Venkat""Hyderabad""111111111");

            dt.Rows.Add(3"Namit""Pune""1222222222");

            dt.Rows.Add(4"Abhinav""Bhagalpur""3333333333");

 

            string address = string.Empty;

            string Name = string.Empty;

 

            var query = (from table in dt.AsEnumerable()

                         select new

                         {

                             studendID = table.Field<string>("Address"),

                             Name = table.Field<string>("StudentName")

 

                         }).ToList();

 

            DataTable converDt = LinqQueryToDataTable(query);

        }

 

        public static DataTable LinqQueryToDataTable(IEnumerable<dynamic> v)

        {

            //We really want to know if there is any data at all

            var firstRecord = v.FirstOrDefault();

            if (firstRecord == null)

                return null;

 

            //So dear record, what do you have?

            PropertyInfo[] infos = firstRecord.GetType().GetProperties();

 

            //Our table should have the columns to support the properties

            DataTable table = new DataTable();

 

            //Add, add, add the columns

            foreach (var info in infos)

            {

 

                Type propType = info.PropertyType;

 

             //Nullable types should be handled too

                if (propType.IsGenericType

                    && propType.GetGenericTypeDefinition() == typeof(Nullable<>))

                {

                    table.Columns.Add(info.Name, Nullable.GetUnderlyingType(propType));

                }

                else

                {

                    table.Columns.Add(info.Name, info.PropertyType);

                }

            }

 

            DataRow row;

 

            foreach (var record in v)

            {

                row = table.NewRow();

                for (int i = 0; i < table.Columns.Count; i++)

                {

                    row[i] = infos[i].GetValue(record) != null ?

 infos[i].GetValue(record) : DBNull.Value;

                }

 

                table.Rows.Add(row);

            }

 

            //Table is ready to serve.

            table.AcceptChanges();

 

            return table;

        }

    }

}

 

Colored by Color Scripter

cs


실행 결과




위와 같이 convertDt 변수에 ToList로 저장되어 있는 List들의 정보들이 DataTable에 알맞게 저장된 것을 확인하실 수 있습니다.


실행 결과에서 convertDt 변수에 저장되어 있는 값을 보는 방법은 DataSet 시각화 도우미를 이용하여 내부 데이터를 확인하였습니다!

 

LinqQueryToDataTable 메서드를 잘 활용하면, ListDataTable로 변환할 경우에 매우 유용하게 사용하실 수 있을거에요~!!

 

글 읽어 주셔서 감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY