Datatable 转化为 ToList() 扩展类 DatatableExtension 【扩展】

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;

namespace SessionKeyGet.Extensions
{
    public static class DatatableExtension
    {
        public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in props)
            {
                if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType));
                else
                    table.Columns.Add(prop.Name, prop.PropertyType);
            }
            foreach (T item in data)
            {
                object[] values = new object[props.Count];
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }
    }
}

 

posted @ 2013-05-09 16:52  xust  阅读(424)  评论(1编辑  收藏  举报