public static class Mapper
{
public static IEnumerable<T> DtToModels<T>(this DataTable dt) where T : class, new()
{
//判断datatable是否有值
if (dt.Columns.Count < 1 || dt.Rows.Count < 1)
{ yield break; }
else
{
var propertyInfos = from propertyInfo in typeof(T).GetProperties()
where dt.Columns.Contains(propertyInfo.Name)
select propertyInfo;
//循环设置属性
foreach (DataRow dr in dt.Rows)//遍历dt中所有行
{
var result = new T();
foreach (var p in propertyInfos)//遍历所有属性
{
try
{
if (p.PropertyType.Name == "Int64")
{
p.SetValue(result, dr[p.Name] == DBNull.Value ? 0 : Convert.ToInt64(dr[p.Name]), null);
}
else if (p.PropertyType.Name == "Int32")
{
p.SetValue(result, dr[p.Name] == DBNull.Value ? 0 : Convert.ToInt32(dr[p.Name]), null);
}
else if (p.PropertyType.Name == "Decimal")
{
p.SetValue(result, dr[p.Name] == DBNull.Value ? 0 : Convert.ToDecimal(dr[p.Name]), null);
}
else
{
p.SetValue(result, dr[p.Name] == DBNull.Value ? null : dr[p.Name], null);
}
}
catch (System.Exception)
{
throw;
}
}
yield return result;
}
}
}
}
使用: