亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#中DataTable 轉(zhuǎn)實(shí)體實(shí)例詳解

 更新時間:2017年04月23日 09:34:07   作者:Langu  
這篇文章主要介紹了C#中DataTable 轉(zhuǎn)實(shí)體實(shí)例詳解,需要的朋友可以參考下

因?yàn)長inq的查詢功能很強(qiáng)大,所以從數(shù)據(jù)庫中拿到的數(shù)據(jù)為了處理方便,我都會轉(zhuǎn)換成實(shí)體集合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);
      //硬編碼,效率比較高,但靈活性不夠,如果實(shí)體改變了,都需要修改代碼
      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>
    /// 查詢數(shù)據(jù)
    /// </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; }
  }
}

后來用反射來做這,對實(shí)體的屬性用反射去賦值,這樣就可以對所有的實(shí)體通用,且增加屬性后不用修改代碼。

程序如下:

static class EntityConvert
  {
    /// <summary>
    /// DataTable轉(zhuǎn)為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;
    }
  }

增加一個擴(kuò)展方法,程序更加通用。但效率不怎么樣,100萬行數(shù)據(jù)【只有兩列】,轉(zhuǎn)換需要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();
    }

速度確實(shí)快了很多,我電腦測試了一下,需要 0.4秒。但問題又來了,這個只能用于Usr這個類,得想辦法把這個類抽象成泛型T,既有委托的高效,又有泛型的通用。

問題就在動態(tài)地產(chǎn)生上面的委托了,經(jīng)過一下午的折騰終于折騰出來了動態(tài)產(chǎn)生委托的方法。主要用到了動態(tài)Lambda表達(dá)式

public static class EntityConverter
  {
    /// <summary>
    /// DataTable生成實(shí)體
    /// </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", "當(dāng)前對象為null無法生成表達(dá)式樹");
      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>
    /// 生成表達(dá)式
    /// </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", "當(dāng)前對象為null 無法轉(zhuǎn)換成實(shí)體");
      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();
    }
  }

 經(jīng)過測試,用這個方法在同樣的條件下轉(zhuǎn)換實(shí)體需要 0.47秒。除了第一次用反射生成Lambda表達(dá)式外,后續(xù)的轉(zhuǎn)換直接用的表達(dá)式。

以上所述是小編給大家介紹的C#中DataTable 轉(zhuǎn)實(shí)體實(shí)例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • Unity實(shí)現(xiàn)UI漸變效果

    Unity實(shí)現(xiàn)UI漸變效果

    這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)UI漸變效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • 使用DateTime的ParseExact方法實(shí)現(xiàn)特殊日期時間的方法詳解

    使用DateTime的ParseExact方法實(shí)現(xiàn)特殊日期時間的方法詳解

    本篇文章是對使用DateTime的ParseExact方法實(shí)現(xiàn)特殊日期時間的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-05-05
  • 在C#中實(shí)現(xiàn)接口事件的具體示例

    在C#中實(shí)現(xiàn)接口事件的具體示例

    在C#中,接口(interface)是一種定義類必須實(shí)現(xiàn)的方法和屬性的抽象類型,除了方法和屬性,接口還可以包含事件,實(shí)現(xiàn)接口事件可以幫助我們設(shè)計(jì)更加靈活和解耦的系統(tǒng),本文將詳細(xì)探討如何在C#中實(shí)現(xiàn)接口事件,并通過具體示例說明其應(yīng)用,需要的朋友可以參考下
    2024-08-08
  • C# 結(jié)合 Javascript 測試獲取天氣信息

    C# 結(jié)合 Javascript 測試獲取天氣信息

    本文將介紹如何使用 C# 并結(jié)合 JavaScript 獲取天氣信息,獲取的數(shù)據(jù)來源于360瀏覽器首頁數(shù)據(jù),對C# 獲取天氣信息示例代碼感興趣的朋友一起看看吧
    2024-08-08
  • Unity shader實(shí)現(xiàn)高斯模糊效果

    Unity shader實(shí)現(xiàn)高斯模糊效果

    這篇文章主要為大家詳細(xì)介紹了Unity shader實(shí)現(xiàn)高斯模糊效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-02-02
  • C#開發(fā)Windows UWP系列之3D變換

    C#開發(fā)Windows UWP系列之3D變換

    這篇文章介紹了C#開發(fā)Windows UWP系列之3D變換,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • C# WPF 建立無邊框(標(biāo)題欄)的登錄窗口的示例

    C# WPF 建立無邊框(標(biāo)題欄)的登錄窗口的示例

    這篇文章主要介紹了C# WPF 建立無邊框(標(biāo)題欄)的登錄窗口的示例,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下
    2020-12-12
  • C#開發(fā)紐曼USB來電小秘書客戶端總結(jié)

    C#開發(fā)紐曼USB來電小秘書客戶端總結(jié)

    這篇文章主要介紹了C#開發(fā)紐曼USB來電小秘書客戶端總結(jié),對于C#項(xiàng)目開發(fā)來說有一定的參考借鑒價值,需要的朋友可以參考下
    2014-08-08
  • C# 分支與循環(huán)介紹

    C# 分支與循環(huán)介紹

    在C# 程序中有三種結(jié)構(gòu): 順序結(jié)構(gòu),分支結(jié)構(gòu),循環(huán)結(jié)構(gòu)。
    2013-04-04
  • C# double類型變量比較分析

    C# double類型變量比較分析

    這篇文章主要介紹了C# double類型變量比較分析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12

最新評論