速度确实快了很多,我电脑测试了一下,需要 0.4秒。但问题又来了,这个只能用于Usr这个类,得想办法把这个类抽象成泛型T,既有委托的高效,又有泛型的通用。
问题就在动态地产生上面的委托了,经过一下午的折腾终于折腾出来了动态产生委托的方法。主要用到了动态Lambda表达式
public static class EntityConverter
{
/// <summary>
/// DataTable生成实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataTable"></param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dataTable) where T : class, new()
{
if (dataTable == null || dataTable.Rows.Count <= 0) throw new ArgumentNullException("dataTable", "当前对象为null无法生成表达式树");
Func<DataRow, T> func = dataTable.Rows[0].ToExpression<T>();
List<T> collection = new List<T>(dataTable.Rows.Count);
foreach (DataRow dr in dataTable.Rows)
{
collection.Add(func(dr));
}
return collection;
}
/// <summary>
/// 生成表达式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataRow"></param>
/// <returns></returns>
public static Func<DataRow, T> ToExpression<T>(this DataRow dataRow) where T : class, new()
{
if (dataRow == null) throw new ArgumentNullException("dataRow", "当前对象为null 无法转换成实体");
ParameterExpression paramter = Expression.Parameter(typeof(DataRow), "dr");
List<MemberBinding> binds = new List<MemberBinding>();
for (int i = 0; i < dataRow.ItemArray.Length; i++)
{
String colName = dataRow.Table.Columns[i].ColumnName;
PropertyInfo pInfo = typeof(T).GetProperty(colName);
if (pInfo == null) continue;
MethodInfo mInfo = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(String) }).MakeGenericMethod(pInfo.PropertyType);
MethodCallExpression call = Expression.Call(mInfo, paramter, Expression.Constant(colName, typeof(String)));
MemberAssignment bind = Expression.Bind(pInfo, call);
binds.Add(bind);
}
MemberInitExpression init = Expression.MemberInit(Expression.New(typeof(T)), binds.ToArray());
return Expression.Lambda<Func<DataRow, T>>(init, paramter).Compile();
}
}
经过测试,用这个方法在同样的条件下转换实体需要 0.47秒。除了第一次用反射生成Lambda表达式外,后续的转换直接用的表达式。
以上所述是小编给大家介绍的C#中DataTable 转实体实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对ASPKU网站的支持!










