实体类集合转成DataTable

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             var list = new List<Demo> {  
 6                    new Demo{ id=1,age=18, name="Tim"},  
 7                     new Demo{ id=2,age=22, name="Allen"},  
 8                    new Demo{ id=3,age=24, name="Jim"}  
 9                };
10             var dt = list.ToDataTable();
11            
12         }
13     }
14     static class Extensions
15     {
16         internal static DataTable ToDataTable<T>(this IList<T> list)
17         {
18             Type elementType = typeof(T);
19  
20             var t = new DataTable();
21  
22             elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
23             foreach (T item in list)
24             {
25                 var row = t.NewRow();
26                 elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
27                 t.Rows.Add(row);
28             }
29             return t;
30         }
31     }
32     class Demo
33     {
34         public int id { get; set; }
35         public string name { get; set; }
36         public int age { get; set; }
37     }  
// 此代码转于 http://bbs.csdn.net/topics/390385021?page=1 q107770540大神的回复

 

posted @ 2013-12-17 16:13  寂小魔  阅读(344)  评论(0编辑  收藏  举报