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

集合转datatable

时间:2015-12-03 11:44:10      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

public static class IEnumerableExtensions
   {
       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/hbsfgl/p/5015403.html

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