码迷,mamicode.com
首页 > 其他好文 > 详细

泛型转Datatable

时间:2015-05-13 18:31:47      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

  //自定义扩展方法
    public static class ExtMethod
    {
     //泛型转为DataTable
        public static DataTable AsDataTable<T>(this IEnumerable<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            var table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;
        }
    }

 

泛型转Datatable

标签:

原文地址:http://www.cnblogs.com/BABLOVE/p/4500809.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!