因為Linq的查詢功能很強大,所以從數據庫中拿到的數據為了處理方便,我都會轉換成實體集合List<T>。
開始用的是硬編碼的方式,好理解,但通用性極低,下面是控件台中的代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace Demo1 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 DataTable dt = Query(); 15 List<Usr> usrs = new List<Usr>(dt.Rows.Count); 16 //硬編碼,效率比較高,但靈活性不夠,如果實體改變了,都需要修改代碼 17 foreach (DataRow dr in dt.Rows) 18 { 19 Usr usr = new Usr { ID = dr.Field<Int32?>("ID"), Name = dr.Field<String>("Name") }; 20 usrs.Add(usr); 21 } 22 usrs.Clear(); 23 } 24 25 /// <summary> 26 /// 查詢數據 27 /// </summary> 28 /// <returns></returns> 29 private static DataTable Query() 30 { 31 DataTable dt = new DataTable(); 32 dt.Columns.Add("ID", typeof(Int32)); 33 dt.Columns.Add("Name", typeof(String)); 34 for (int i = 0; i < 1000000; i++) 35 { 36 dt.Rows.Add(new Object[] { i, Guid.NewGuid().ToString() }); 37 } 38 return dt; 39 } 40 } 41 class Usr 42 { 43 public Int32? ID { get; set; } 44 public String Name { get; set; } 45 } 46 }
后來用反射來做這,對實體的屬性用反射去賦值,這樣就可以對所有的實體通用,且增加屬性后不用修改代碼。
程序如下:
1 static class EntityConvert 2 { 3 /// <summary> 4 /// DataTable轉為List<T> 5 /// </summary> 6 /// <typeparam name="T"></typeparam> 7 /// <param name="dt"></param> 8 /// <returns></returns> 9 public static List<T> ToList<T>(this DataTable dt) where T : class, new() 10 { 11 List<T> colletion = new List<T>(); 12 PropertyInfo[] pInfos = typeof(T).GetProperties(); 13 foreach (DataRow dr in dt.Rows) 14 { 15 T t = new T(); 16 foreach (PropertyInfo pInfo in pInfos) 17 { 18 if (!pInfo.CanWrite) continue; 19 pInfo.SetValue(t, dr[pInfo.Name]); 20 } 21 colletion.Add(t); 22 } 23 return colletion; 24 } 25 }
增加一個擴展方法,程序更加通用。但效率不怎么樣,100萬行數據【只有兩列】,轉換需要2秒
后來想到用委托去做 委托原型如下
1 Func<DataRow, Usr> func = dr => new Usr { ID = dr.Field<Int32?>("ID"), Name = dr.Field<String>("Name") };
代碼如下:
1 static void Main(string[] args) 2 { 3 DataTable dt = Query(); 4 Func<DataRow, Usr> func = dr => new Usr { ID = dr.Field<Int32?>("ID"), Name = dr.Field<String>("Name") }; 5 List<Usr> usrs = new List<Usr>(dt.Rows.Count); 6 Stopwatch sw = Stopwatch.StartNew(); 7 foreach (DataRow dr in dt.Rows) 8 { 9 Usr usr = func(dr); 10 usrs.Add(usr); 11 } 12 sw.Stop(); 13 Console.WriteLine(sw.ElapsedMilliseconds); 14 usrs.Clear(); 15 Console.ReadKey(); 16 }
速度確實快了很多,我電腦測試了一下,需要 0.4秒。但問題又來了,這個只能用於Usr這個類,得想辦法把這個類抽象成泛型T,既有委托的高效,又有
泛型的通用。
問題就在動態地產生上面的委托了,經過一下午的折騰終於折騰出來了動態產生委托的方法。主要用到了動態Lambda表達式
1 public static class EntityConverter 2 { 3 /// <summary> 4 /// DataTable生成實體 5 /// </summary> 6 /// <typeparam name="T"></typeparam> 7 /// <param name="dataTable"></param> 8 /// <returns></returns> 9 public static List<T> ToList<T>(this DataTable dataTable) where T : class, new() 10 { 11 if (dataTable == null || dataTable.Rows.Count <= 0) throw new ArgumentNullException("dataTable", "當前對象為null無法生成表達式樹"); 12 Func<DataRow, T> func = dataTable.Rows[0].ToExpression<T>(); 13 List<T> collection = new List<T>(dataTable.Rows.Count); 14 foreach (DataRow dr in dataTable.Rows) 15 { 16 collection.Add(func(dr)); 17 } 18 return collection; 19 } 20 21 /// <summary> 22 /// 生成表達式 23 /// </summary> 24 /// <typeparam name="T"></typeparam> 25 /// <param name="dataRow"></param> 26 /// <returns></returns> 27 public static Func<DataRow, T> ToExpression<T>(this DataRow dataRow) where T : class, new() 28 { 29 if (dataRow == null) throw new ArgumentNullException("dataRow", "當前對象為null 無法轉換成實體"); 30 ParameterExpression paramter = Expression.Parameter(typeof(DataRow), "dr"); 31 List<MemberBinding> binds = new List<MemberBinding>(); 32 for (int i = 0; i < dataRow.ItemArray.Length; i++) 33 { 34 String colName = dataRow.Table.Columns[i].ColumnName; 35 PropertyInfo pInfo = typeof(T).GetProperty(colName); 36 if (pInfo == null) continue; 37 MethodInfo mInfo = typeof(DataRowExtensions).GetMethod("Field", new Type[] { typeof(DataRow), typeof(String) }).MakeGenericMethod(pInfo.PropertyType); 38 MethodCallExpression call = Expression.Call(mInfo, paramter, Expression.Constant(colName, typeof(String))); 39 MemberAssignment bind = Expression.Bind(pInfo, call); 40 binds.Add(bind); 41 } 42 MemberInitExpression init = Expression.MemberInit(Expression.New(typeof(T)), binds.ToArray()); 43 return Expression.Lambda<Func<DataRow, T>>(init, paramter).Compile(); 44 } 45 }
經過測試,用這個方法在同樣的條件下轉換實體需要 0.47秒。除了第一次用反射生成Lambda表達式外,后續的轉換直接用的表達式。
原創作品,轉載請注明出處:http://www.cnblogs.com/lclblog/p/6701814.html