■ DataTable 클래스를 사용해 데이터 테이블에서 객체 리스트를 구하는 방법을 보여준다.
▶ DataTable 클래스 : 데이터 테이블에서 객체 리스트 구하기 예제 (C#)
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 |
using System; using System.Collections.Generic; using System.Data; DataTable table = new DataTable(); table.Columns.Add("ID" , typeof(int )); table.Columns.Add("Name", typeof(string)); table.Rows.Add(1, "김철수"); table.Rows.Add(2, "이철희"); table.Rows.Add(3, "홍길동"); table.Rows.Add(4, "이미영"); table.Rows.Add(5, "이명숙"); table.AcceptChanges(); List<Employee> list = GetList<Employee>(table); for(int i = 0; i < list.Count; i++) { Employee employee = list[i]; Console.WriteLine(employee.Name); } |
▶ DataTable 클래스 : 데이터 테이블에서 객체 리스트 구하기 (C#)
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 93 94 95 96 97 |
using System; using System.Collections.Generic; using System.Reflection; using System.Data; #region 리스트 구하기 - GetList<T>(sourceTable) /// <summary> /// 리스트 구하기 /// </summary> /// <typeparam name="T">객체 타입</typeparam> /// <param name="sourceTable">소스 테이블</param> /// <returns>리스트</returns> public List<T> GetList<T>(DataTable sourceTable) where T : new() { Type targetType = typeof(T); List<T> targetList = new List<T>(); foreach(DataRow sourceRow in sourceTable.Rows) { T targetObject = GetObject<T>(sourceRow); targetList.Add(targetObject); } return targetList; } #endregion #region 객체 구하기 - GetObject<T>(sourceRow) /// <summary> /// 객체 구하기 /// </summary> /// <typeparam name="T">객체 타입</typeparam> /// <param name="sourceRow">소스 행</param> /// <returns>객체</returns> private T GetObject<T>(DataRow sourceRow) where T : new() { Type targetType = typeof(T); T targetObject = new T(); foreach(DataColumn sourceColumn in sourceRow.Table.Columns) { string columnName = sourceColumn.ColumnName; PropertyInfo propertyInfo = targetType.GetProperty ( columnName.ToLower(), BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance ); if(propertyInfo != null) { object columnValue = sourceRow[columnName]; bool isNullable = (Nullable.GetUnderlyingType(propertyInfo.PropertyType) != null); if(isNullable) { if(columnValue is DBNull) { columnValue = null; } else { columnValue = Convert.ChangeType ( columnValue, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ); } } else { if(columnValue is DBNull) { columnValue = null; } else { columnValue = Convert.ChangeType(columnValue, propertyInfo.PropertyType); } } propertyInfo.SetValue(targetObject, columnValue, null); } } return targetObject; } #endregion |