国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

將DataTable轉換成List<T>實現思路及示例代碼

2020-01-24 03:05:33
字體:
來源:轉載
供稿:網友

前幾天在工作中,遇到一個問題:需要將查詢出來的DataTable數據源,轉換成List<T>的泛型集合(已知T類型)。第一反應,我想肯定要用到“泛型”(這不是廢話嗎?都說了要轉換成List<T>泛型集合了),而且還要用到“反射”相關的。呵呵。很快,我就做出了一個小實例,測試通過。下面我將代碼貼出來,分享給大家。代碼都有詳細的注釋,讀者朋友可以很清晰的看懂我的思路。

首先,這是我寫的一個通用轉換類,完成此類操作。也是實現這個功能最核心的部分:

復制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Reflection;
namespace DatableToList
{
    class ConvertHelper<T> where T : new()
    {
        /// <summary>
        /// 利用反射和泛型
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ConvertToList(DataTable dt)
        {

            // 定義集合
            List<T> ts = new List<T>();

            // 獲得此模型的類型
            Type type = typeof(T);
            //定義一個臨時變量
            string tempName = string.Empty;
            //遍歷DataTable中所有的數據行
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 獲得此模型的公共屬性
                PropertyInfo[] propertys = t.GetType().GetProperties();
                //遍歷該對象的所有屬性
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;//將屬性名稱賦值給臨時變量
                    //檢查DataTable是否包含此列(列名==對象的屬性名) 
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判斷此屬性是否有Setter
                        if (!pi.CanWrite) continue;//該屬性不可寫,直接跳出
                        //取值
                        object value = dr[tempName];
                        //如果非空,則賦給對象的屬性
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                //對象添加到泛型集合中
                ts.Add(t);
            }

            return ts;

        }
    }
}


下面,是Main方法中調用的實例:
復制代碼 代碼如下:

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


namespace DatableToList
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = CreateDt();//獲得一個DataTable
          //根據對象類型和DataTable,獲取泛型集合
          List<Person>  list = ConvertHelper<Person>.ConvertToList(dt);
          //遍歷該泛型集合,打印輸出。
        foreach (var item in list)
        {
            Console.WriteLine(item.ToString());
        }

          Console.ReadKey();
        }
        /// <summary>
        /// 創建一個DataTable,并添加數據,提供測試。
        /// </summary>
        /// <returns></returns>
        public static DataTable CreateDt()
        {

            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("id", typeof(System.Int32)));
            dt.Columns.Add(new DataColumn("name", typeof(System.String)));
            dt.Columns.Add(new DataColumn("address", typeof(System.String)));

            dt.Rows.Add(1,"Dylan","SZ");
            dt.Rows.Add(2, "Jay", "TW");
            dt.Rows.Add(3, "CQ", "HK");
            return dt;
        }

    }  

}


最下面,就是自定義的一個簡單類的代碼了:
復制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DatableToList
{
    class Person
    {
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string address;

        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        public override string ToString()
        {
            return "Person: " + id + " ," + name+","+address;
        }
    }
}


上面的例子測試通過,水平有限,不足之處,敬請諒解。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 通榆县| 海伦市| 拉孜县| 陇南市| 门头沟区| 马公市| 和田县| 金山区| 阳谷县| 梁平县| 囊谦县| 修水县| 新兴县| 正阳县| 和平县| 龙川县| 柳林县| 山东| 册亨县| 江口县| 龙海市| 讷河市| 华亭县| 崇左市| 寿光市| 桃园市| 新民市| 赤壁市| 阳曲县| 郑州市| 岑溪市| 雷波县| 温宿县| 沐川县| 蒲江县| 宁国市| 疏附县| 大邑县| 柯坪县| 七台河市| 东宁县|