namespace jdrz.HumanIdentify
{
public class Helper
{
/// <summary>
/// DataTable 轉(zhuǎn)換為L(zhǎng)ist 集合
/// </summary>
/// <typeparam name="TResult">類型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<TResult> ToList<TResult>(DataTable dt) where TResult : class, new()
{
//創(chuàng)建一個(gè)屬性的列表
var prlist = new List<PropertyInfo>();
//獲取TResult的類型實(shí)例 反射的入口
var t = typeof(TResult);
//獲得TResult 的所有的Public 屬性 并找出TResult屬性和DataTable的列名稱相同的屬性(PropertyInfo) 并加入到屬性列表
Array.ForEach(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
//創(chuàng)建返回的集合
var oblist = new List<TResult>();
foreach (DataRow row in dt.Rows)
{
//創(chuàng)建TResult的實(shí)例
var ob = new TResult();
//找到對(duì)應(yīng)的數(shù)據(jù) 并賦值
prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
//放入到返回的集合中.
oblist.Add(ob);
}
return oblist;
}
}
}
新聞熱點(diǎn)
疑難解答
圖片精選