Convert DataTable to Listlt; Tgt; Implementation ideas and sample code

  • 2020-05-24 06:03:12
  • OfStack

A few days ago, I encountered a problem in my work: I needed to convert the DataTable data source that was queried into List < T > Is a generic collection of known T types. Reaction 1, I'm sure you need to use generics (isn't that bullshit? I said I'm going to convert to List < T > Generics are set), and you need to use "reflection" related. Ha ha. Soon, I made a small example, the test passed. Let me post the code and share it with you. The code has detailed comments, readers can clearly understand my ideas.

First, this is a generic transformation class that I wrote to do this. It is also the core part of implementing this function:


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>
        ///  Use reflection and generics 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ConvertToList(DataTable dt)
        {
            //  Define a collection 
            List<T> ts = new List<T>();
            //  Gets the type of this model 
            Type type = typeof(T);
            // define 1 Three temporary variables 
            string tempName = string.Empty;
            // traverse DataTable All the data rows in 
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                //  Get the common properties for this model 
                PropertyInfo[] propertys = t.GetType().GetProperties();
                // Traverse all the properties of the object 
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;// Assign the property name to a temporary variable 
                    // check DataTable Contains this column (column name == Object property name)   
                    if (dt.Columns.Contains(tempName))
                    {
                        //  Determine if this property is present Setter
                        if (!pi.CanWrite) continue;// This property is not writable 
                        // The values 
                        object value = dr[tempName];
                        // If not empty, the property assigned to the object 
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                // Object is added to a generic collection 
                ts.Add(t);
            }
            return ts;
        }
    }
}

Below, is the instance called in the Main method:

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();// To obtain 1 a DataTable
          // By object type and DataTable , get the generic collection 
          List<Person>  list = ConvertHelper<Person>.ConvertToList(dt);
          // Walk through the generic collection and print the output. 
        foreach (var item in list)
        {
            Console.WriteLine(item.ToString());
        }
          Console.ReadKey();
        }
        /// <summary>
        ///  create 1 a DataTable And add data to provide tests. 
        /// </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;
        }
    }   

}

At the bottom, is the custom 1 simple class code:

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

The above example passed the test, the level is limited, the deficiency, please forgive me.


Related articles: