如何將DataTable轉換成List 呢?


昨日在工作中,遇到一個問題:需要將查詢出來的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;
        }
    }
}

http://blog.csdn.net/dinglang_2009/article/details/6951138


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM