1 /// <summary> 2 /// EF模型转换为Datatable 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="list"></param> 6 /// <returns></returns> 7 public static DataTable EFModToDataTable<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 }
标签:info,C#,EF,properties,dataTable,PropertyType,new,DataTable From: https://www.cnblogs.com/smartnn/p/16771602.html