欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c#的datatable轉(zhuǎn)list示例

 更新時(shí)間:2014年04月03日 09:47:06   作者:  
這篇文章主要介紹了c#的datatable轉(zhuǎn)list示例,代碼中有注釋,需要的朋友可以參考下

復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

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;
        }
    }
}

相關(guān)文章

最新評(píng)論