using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
#region 데이터 테이블 구하기 - GetDataTable<TSource>(sourceList)
/// <summary>
/// 데이터 테이블 구하기
/// </summary>
/// <typeparam name="TSource">소스 타입</typeparam>
/// <param name="sourceList">소스 리스트</param>
/// <returns>데이터 테이블</returns>
public DataTable GetDataTable<TSource>(IList<TSource> sourceList)
{
DataTable targetTable = GetDataTable<TSource>(); // '객체 타입을 갖고 데이터 테이블 구하기' 참조
Type sourceType = typeof(TSource);
PropertyDescriptorCollection sourcePDC = TypeDescriptor.GetProperties(sourceType);
foreach(TSource item in sourceList)
{
DataRow targetRow = targetTable.NewRow();
foreach(PropertyDescriptor propertyDescriptor in sourcePDC)
{
targetRow[propertyDescriptor.Name] = propertyDescriptor.GetValue(item);
}
targetTable.Rows.Add(targetRow);
}
return targetTable;
}
#endregion
#region 데이터 테이블 구하기 - GetDataTable<TSource>()
/// <summary>
/// 데이터 테이블 구하기
/// </summary>
/// <typeparam name="TSource">소스 타입</typeparam>
/// <returns>데이터 테이블</returns>
public DataTable GetDataTable<TSource>()
{
Type sourceType = typeof(TSource);
DataTable targetTable = new DataTable(sourceType.Name);
PropertyDescriptorCollection sourcePDC = TypeDescriptor.GetProperties(sourceType);
foreach(PropertyDescriptor propertyDescriptor in sourcePDC)
{
targetTable.Columns.Add(propertyDescriptor.Name, propertyDescriptor.PropertyType);
}
return targetTable;
}
#endregion
[ex] 다른 예 - 압축본
public DataSet ConvertToDataSet(IList list)
{
DataSet dsFromDtStru = new DataSet();
DataTable table = new DataTable();
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo prop in properties)
{
table.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyInfo prop in properties)
{
row[prop.Name] = prop.GetValue(item, null) == null ? DBNull.Value : prop.GetValue(item, null);
}
table.Rows.Add(row);
}
dsFromDtStru.Tables.Add(table);
return dsFromDtStru;
}
'SW > C#' 카테고리의 다른 글
[C#] DataTable에서 유용하게 사용 되는 것들 (0) | 2019.12.16 |
---|---|
[C#] Dataset 을 엑셀파일로 다운로드 (0) | 2019.09.19 |
[C#] HTTP/HTTPS 송수신 (HttpWebRequest/HttpWebResponse) (0) | 2019.09.19 |