C# List集合转DataTable

 1         /// <summary>
 2         /// List集合转DataTable
 3         /// </summary>
 4         /// <typeparam name="T">实体类型</typeparam>
 5         /// <param name="list">传入集合</param>
 6         /// <param name="isStoreDB">是否存入数据库DateTime字段,date时间范围没事,取出展示不用设置TRUE</param>
 7         /// <returns>返回datatable结果</returns>
 8         public static DataTable ListToTable<T>(List<T> list, bool isStoreDB = true)
 9         {
10             Type tp = typeof(T);
11             PropertyInfo[] proInfos = tp.GetProperties();
12             DataTable dt = new DataTable();
13             foreach (var item in proInfos)
14             {
15                 dt.Columns.Add(item.Name, item.PropertyType); //添加列明及对应类型
16             }
17             foreach (var item in list)
18             {
19                 DataRow dr = dt.NewRow();
20                 foreach (var proInfo in proInfos)
21                 {
22                     object obj = proInfo.GetValue(item);
23                     if (obj == null)
24                     {
25                         continue;
26                     }
27                     //if (obj != null)
28                     // {
29                     if (isStoreDB && proInfo.PropertyType == typeof(DateTime) &&  Convert.ToDateTime(obj) < Convert.ToDateTime("1753-01-01"))
30                     {
31                         continue;
32                     }
33                     // dr[proInfo.Name] = proInfo.GetValue(item);
34                     dr[proInfo.Name] = obj;
35                     // }
36                 }
37                 dt.Rows.Add(dr);
38             }
39             return dt;
40         }        

 

C# List集合转DataTable

上一篇:photoshop鼠绘iPhone 4s语音助理Siri图标


下一篇:Freehand 实用秘技 15个Freehand功能介绍