public static DataTable ToDataTable<T>(this List<T> list)
{
DataTable result = new DataTable();
List<PropertyInfo> pList = new List<PropertyInfo>();
Type type = typeof(T);
Array.ForEach<PropertyInfo>(type.GetProperties(), prop => { pList.Add(prop); result.Columns.Add(prop.Name, prop.PropertyType); });
foreach (var item in list)
{
DataRow row = result.NewRow();
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
result.Rows.Add(row);
}
return result;
}
public static List<T> ToList<T>(this DataTable table) where T : class, new()
{
List<T> result = new List<T>();
List<PropertyInfo> pList = new List<PropertyInfo>();
Type type = typeof(T);
Array.ForEach<PropertyInfo>(type.GetProperties(), prop => { if (table.Columns.IndexOf(prop.Name) != -1) pList.Add(prop); });
foreach (DataRow row in table.Rows)
{
T obj = new T();
pList.ForEach(prop => { if (row[prop.Name] != DBNull.Value) prop.SetValue(obj, row[prop.Name], null); });
result.Add(obj);
}
return result;
}
标签:List,prop,result,泛型,new,DataTable,row
From: https://www.cnblogs.com/ksq1063/p/18291599