因為Linq的查詢功能很強大,所以從數據庫中拿到的數據為了處理方便,我都會轉換成實體集合List<T>。
開始用的是硬編碼的方式,好理解,但通用性極低,下面是控件臺中的代碼:
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<Usr> usrs = new List<Usr>(dt.Rows.Count);      //硬編碼,效率比較高,但靈活性不夠,如果實體改變了,都需要修改代碼      foreach (DataRow dr in dt.Rows)      {        Usr usr = new Usr { ID = dr.Field<Int32?>("ID"), Name = dr.Field<String>("Name") };        usrs.Add(usr);      }      usrs.Clear();    }    /// <summary>    /// 查詢數據    /// </summary>    /// <returns></returns>    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  {    /// <summary>    /// DataTable轉為List<T>    /// </summary>    /// <typeparam name="T"></typeparam>    /// <param name="dt"></param>    /// <returns></returns>    public static List<T> ToList<T>(this DataTable dt) where T : class, new()    {      List<T> colletion = new List<T>();      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秒
后來想到用委托去做 委托原型如下
Func<DataRow, Usr> func = dr => new Usr { ID = dr.Field<Int32?>("ID"), Name = dr.Field<String>("Name") };代碼如下:
static void Main(string[] args)    {      DataTable dt = Query();      Func<DataRow, Usr> func = dr => new Usr { ID = dr.Field<Int32?>("ID"), Name = dr.Field<String>("Name") };      List<Usr> usrs = new List<Usr>(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  {    /// <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 轉實體實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答