首页 > 其他分享 >ListToDataTable

ListToDataTable

时间:2023-05-06 14:25:44浏览次数:31  
标签:prop item foreach ListToDataTable var dt row

 1 /// <summary>
 2 /// List to DataTable
 3 /// </summary>
 4 /// <typeparam name="T"></typeparam>
 5 /// <param name="list">List数据</param>
 6 /// <returns></returns>
 7 public static System.Data.DataTable ListToDataTable<T>(List<T> list)
 8 {
 9     var props = typeof(T).GetProperties();
10 
11     var dt = new System.Data.DataTable();
12     foreach (var item in props)
13     {
14         dt.Columns.Add(item.Name, item.PropertyType);
15     }
16 
17     foreach (var item in list)
18     {
19         var row = dt.NewRow();
20         foreach (var prop in props)
21         {
22             var val = prop.GetValue(item, null);
23 
24             if (val == null)
25             {
26                 continue;
27             }
28             row[prop.Name] = val;
29         }
30         dt.Rows.Add(row);
31     }
32     return dt;
33 }

 

标签:prop,item,foreach,ListToDataTable,var,dt,row
From: https://www.cnblogs.com/baymaxwh/p/17352128.html

相关文章