DataTable转换成List集合
/// <summary>/// 把Dt转换成实体集合
/// </summary>
/// <typeparam name="T">实体</typeparam>
/// <param name="dt">表</param>
/// <returns></returns>
public List<T> DtOrList<T>(DataTable dt) where T : class , new()
{
try
{
List<T> list = new List<T>();
for (int i = 0; i < dt.Rows.Count; i++)
{
//============================== 创建实体实例并获取实例中的所有公共属性 =========================
T t = Activator.CreateInstance<T>();
PropertyInfo[] PrInfo = t.GetType().GetProperties();
// end========================== 创建实体实例并获取实例中的所有公共属性 =========================
for (int j = 0; j < dt.Columns.Count; j++)
{
foreach (PropertyInfo Info in PrInfo)
{
//====================== 当属性名称和列名相同时对实体字段进行赋值 ========================
if (dt.Columns.ColumnName.ToUpper().Equals(Info.Name.ToUpper()))
{
if (dt.Rows != DBNull.Value)
{
Info.SetValue(t, dt.Rows, null);
}
else
{
Info.SetValue(t, null, null);
}
break;
}
// end================== 当属性名称和列名相同时对实体字段进行赋值 ========================
}
}
list.Add(t);
}
return list;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
此方法转换性能并不是最优的,有兴趣的可以尝试着进行优化
如想要更优的方法,请留言:lol
{:2_31:}好久没看到教程了。。 ibcadmin 发表于 2017-11-15 22:46
好久没看到教程了。。
:lol 大神,总结的很好,学习,谢谢 xie :) ttt job_zhang 发表于 2018-4-16 10:43
ttt
???? 谢谢,大佬分享
页:
[1]