使用反射和动态生成代码两种方式(Reflect和Emit)
反射将DataTable转为List方法
public static List<T> ToListByReflect<T>(this DataTable dt) where T : new()
{
List<T> ts = new List<T>();
string tempName = string.Empty;
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);
}
r