본문 바로가기

SW/C#

[C#] 객체 리스트를 데이터 테이블로 변환하기

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;
}