C# 模型转为DataTable

 1 /// <summary>
 2 /// 模型转为Datatable
 3 /// </summary>
 4 /// <typeparam name="T"></typeparam>
 5 /// <param name="list"></param>
 6 /// <returns></returns>
 7 public static DataTable ModelToDataTable<T>(IEnumerable<T> list)
 8 {
 9     Type type = typeof(T);
10     DataTable dataTable = new DataTable();
11     List<PropertyInfo> properties = new List<PropertyInfo>();
12     foreach (PropertyInfo info in type.GetProperties())
13     {
14         if (info.PropertyType.IsValueType || info.PropertyType == typeof(string))
15         {
16             dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
17             properties.Add(info);
18         }
19     }
20     foreach (T entity in list)
21     {
22         object[] values = new object[properties.Count];
23         for (int i = 0; i < properties.Count; i++)
24         {
25             values[i] = properties[i].GetValue(entity);
26         }
27         dataTable.Rows.Add(values);
28     }
29     return dataTable;
30 }

 

posted @ 2022-10-09 16:53  Mr_Xul  阅读(114)  评论(0)    收藏  举报