因为Linq的查询功能很强大,所以从数据库中拿到的数据为了处理方便,我都会转换成实体集合List
开始用的是硬编码的方式,好理解,但通用性极低,下面是控件台中的代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = Query();
List usrs = new List(dt.Rows.Count);
//硬编码,效率比较高,但灵活性不够,如果实体改变了,都需要修改代码
foreach (DataRow dr in dt.Rows)
{
Usr usr = new Usr { ID = dr.Field("ID"), Name = dr.Field("Name") };
usrs.Add(usr);
}
usrs.Clear();
}
///
/// 查询数据
///
///
private static DataTable Query()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name", typeof(String));
for (int i = 0; i < 1000000; i++)
{
dt.Rows.Add(new Object[] { i, Guid.NewGuid().ToString() });
}
return dt;
}
}
class Usr
{
public Int32? ID { get; set; }
public String Name { get; set; }
}
}
后来用反射来做这,对实体的属性用反射去赋值,这样就可以对所有的实体通用,且增加属性后不用修改代码。
程序如下:
static class EntityConvert
{
///
/// DataTable转为List
///
///
///
///
public static List ToList(this DataTable dt) where T : class, new()
{
List colletion = new List();
PropertyInfo[] pInfos = typeof(T).GetProperties();
foreach (DataRow dr in dt.Rows)
{
T t = new T();
foreach (PropertyInfo pInfo in pInfos)
{
if (!pInfo.CanWrite) continue;
pInfo.SetValue(t, dr[pInfo.Name]);
}
colletion.Add(t);
}
return colletion;
}
}
增加一个扩展方法,程序更加通用。但效率不怎么样,100万行数据【只有两列】,转换需要2秒
后来想到用委托去做 委托原型如下
Funcfunc = dr => new Usr { ID = dr.Field ("ID"), Name = dr.Field ("Name") };
代码如下:
static void Main(string[] args)
{
DataTable dt = Query();
Func func = dr => new Usr { ID = dr.Field("ID"), Name = dr.Field("Name") };
List usrs = new List(dt.Rows.Count);
Stopwatch sw = Stopwatch.StartNew();
foreach (DataRow dr in dt.Rows)
{
Usr usr = func(dr);
usrs.Add(usr);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
usrs.Clear();
Console.ReadKey();
}
速度确实快了很多,我电脑测试了一下,需要 0.4秒。但问题又来了,这个只能用于Usr这个类,得想办法把这个类抽象成泛型T,既有委托的高效,又有泛型的通用。
问题就在动态地产生上面的委托了,经过一下午的折腾终于折腾出来了动态产生委托的方法。主要用到了动态Lambda表达式
public static class EntityConverter
{
///
/// DataTable生成实体
///
///
///
///
public static List ToList(this DataTable dataTable) where T : class, new()
{
if (dataTable == null || dataTable.Rows.Count <= 0) throw new ArgumentNullException("dataTable", "当前对象为null无法生成表达式树");
Func func = dataTable.Rows[0].Toexpression();
List collection = new List(dataTable.Rows.Count);
foreach (DataRow dr in dataTable.Rows)
{
collection.Add(func(dr));
}
return collection;
}
///
/// 生成表达式
///
///
///
///
public static Func Toexpression(this DataRow dataRow) where T : class, new()
{
if (dataRow == null) throw new ArgumentNullException("dataRow", "当前对象为null 无法转换成实体");
Parameterexpression paramter = expression.Parameter(typeof(DataRow), "dr");
List binds = new List();
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>(init, paramter).Compile();
}
}
经过测试,用这个方法在同样的条件下转换实体需要 0.47秒。除了第一次用反射生成Lambda表达式外,后续的转换直接用的表达式。
以上所述是小编给大家介绍的C#中DataTable 转实体实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!



