C#中DataTable 轉(zhuǎn)實體實例詳解
因為Linq的查詢功能很強大,所以從數(shù)據(jù)庫中拿到的數(shù)據(jù)為了處理方便,我都會轉(zhuǎn)換成實體集合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>
/// 查詢數(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; }
}
}
后來用反射來做這,對實體的屬性用反射去賦值,這樣就可以對所有的實體通用,且增加屬性后不用修改代碼。
程序如下:
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;
}
}
增加一個擴展方法,程序更加通用。但效率不怎么樣,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();
}
速度確實快了很多,我電腦測試了一下,需要 0.4秒。但問題又來了,這個只能用于Usr這個類,得想辦法把這個類抽象成泛型T,既有委托的高效,又有泛型的通用。
問題就在動態(tài)地產(chǎn)生上面的委托了,經(jīng)過一下午的折騰終于折騰出來了動態(tài)產(chǎn)生委托的方法。主要用到了動態(tài)Lambda表達(dá)式
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", "當(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)換成實體");
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)換實體需要 0.47秒。除了第一次用反射生成Lambda表達(dá)式外,后續(xù)的轉(zhuǎn)換直接用的表達(dá)式。
以上所述是小編給大家介紹的C#中DataTable 轉(zhuǎn)實體實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- C# 實現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼
- C# DataTable與Model互轉(zhuǎn)的示例代碼
- C# DataTable常見用法匯總
- C# ArrayList、HashSet、HashTable、List、Dictionary的區(qū)別詳解
- C#讀取Excel到DataTable的方法示例
- C#實現(xiàn)Json轉(zhuǎn)DataTable并導(dǎo)出Excel的方法示例
- C#使用Datatable導(dǎo)出Excel
- 詳解C#把DataTable中數(shù)據(jù)一次插入數(shù)據(jù)庫的方法
- C# 實現(xiàn)Table的Merge,Copy和Clone
相關(guān)文章
.Net WInform開發(fā)筆記(三)談?wù)勛灾瓶丶?自定義控件)
自定義控件的出現(xiàn)有利于用戶更好的實現(xiàn)自己的想法,可以封裝一些常用的方法,屬性等等,本文詳細(xì)介紹一下自定義控件的實現(xiàn),感興趣的朋友可以了解下2013-01-01
詳解C#批量插入數(shù)據(jù)到Sqlserver中的四種方式
本文主要講解一下在Sqlserver中批量插入數(shù)據(jù)。文中大數(shù)據(jù)批量插入方式一和方式四盡量避免使用,而方式二和方式三都是非常高效的批量插入數(shù)據(jù)方式,需要的朋友可以看下2016-12-12

