public static DataTable ToDataTable<T>(this IEnumerable<T> list) { if (list == null || list.Count() == 0) { return null; } List<PropertyInfo> pList = new List<PropertyInfo>(); Type type = typeof(T); DataTable dt = new DataTable(); Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); foreach (var item in list) { DataRow row = dt.NewRow(); pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); dt.Rows.Add(row); } return dt; }
上面的方法,会出现System.Nullable<>的错误,修改后,如下:
public static class Utility { public static DataTable ToDataTable<T>(this List<T> list) { if (list == null || list.Count == 0) { return null; } //定义一个属性集合 List<PropertyInfo> properties = new List<PropertyInfo>(); Type type = typeof(T); DataTable table = new DataTable(); Array.ForEach<PropertyInfo>(type.GetProperties(), p => { properties.Add(p); //把属性加入到集合 table.Columns.Add(p.Name, p.PropertyType); //添加DataTable的列 }); foreach (var item in list) { //创建DataRow DataRow row = table.NewRow(); //赋值 properties.ForEach(p => row[p.Name] = p.GetValue(item, null)); table.Rows.Add(row); } return table; } }
List<T> 转化为DataTable,使用Array.ForEach()
最新推荐文章于 2021-10-15 14:49:55 发布