写代码的时候经常会将datatable 转为实体list , 我做了一个简单的类,
本人人菜鸟,写错的话请见谅
public class DataConvert
{
public static List<T> DatatableToList<T>(DataTable dt) where T : class, new()
{
List<T> ts = new List<T>();
string tempName = "";
foreach(DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach(PropertyInfo pi in propertys)
{
tempName = pi.Name;
if( dt.Columns.Contains(tempName) )
{
object value = dr[tempName];
if (value != DBNull.Value) {
pi.SetValue(t, value, null);
}
}
}
ts.Add(t);
}//end every data row
return ts;
}
}
备注,头部命名空间要加入
using System.Data;
using System.Reflection;