C#之DataTable转List与List转Datatable

闲来无事,只有写代码啦,以下为DataTable转List与List转DataTable的两个方法,主要技术点用到了反射原理:

    /// <summary>
    /// 模型转换类
    /// </summary>
    public class ConvertModel
    {
        /// <summary>
        /// DataTable转List
        /// </summary>
        /// <typeparam name="T">list中的类型</typeparam>
        /// <param name="dt">要转换的DataTable</param>
        /// <returns></returns>
        public static List<T> DatatTableToList<T>(DataTable dt) where T : class, new()
        {
            List<T> list = new List<T>();
            T t = new T();
            PropertyInfo[] prop = t.GetType().GetProperties();
            //遍历所有DataTable的行
            foreach (DataRow dr in dt.Rows)
            {
                t = new T();
                //通过反射获取T类型的所有成员
                foreach (PropertyInfo pi in prop)
                {
                    //DataTable列名=属性名
                    if (dt.Columns.Contains(pi.Name))
                    {
                        //属性值不为空
                        if (dr[pi.Name] != DBNull.Value)
                        {
                            object value = Convert.ChangeType(dr[pi.Name], pi.PropertyType);
                            //给T类型字段赋值
                            pi.SetValue(t, value, null);
                        }
                    }
                }
                //将T类型添加到集合list
                list.Add(t);
            }
            return list;

        }

        /// <summary>
        /// List转换为DataTable
        /// </summary>
        /// <typeparam name="T">List中的类型</typeparam>
        /// <param name="list">要转换的list</param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> list) where T : class
        {
            DataTable dt = new DataTable();
            PropertyInfo[] prop = typeof(T).GetProperties();
            DataColumn[] ColumnArr = prop.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray();
            dt.Columns.AddRange(ColumnArr);
            foreach (T t in list)
            {
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in prop)
                {
                    if (dt.Columns.Contains(pi.Name))
                    {
                        if (pi.GetValue(t) != null)
                        {
                            dr[pi.Name] = pi.GetValue(t);
                        }
                    }
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }
    }

调用:

            DataTable dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("Sex");
            dt.Columns.Add("Age");
            dt.Columns.Add("Height");
            DataRow dr = dt.NewRow();
            dr["Id"] = 1;
            dr["Sex"] = 1;
            dr["Age"] = 18;
            dr["Height"] = 190;
            dt.Rows.Add(dr);
            //将DataTable转换为List<Persion>
            List<Persion> list1 = ConvertModel.DatatTableToList<Persion>(dt);

            List<Persion> list = new List<Persion>()
            {
                new Persion(){Id=1,Sex=1,Age=26,Height=168},
                new Persion(){Id=2,Sex=0,Age=26,Height=168},
            };
            //将List<Persion>转换为DataTable
            DataTable dt1 = ConvertModel.ListToDataTable<Persion>(list);
时间: 2024-11-08 20:46:58

C#之DataTable转List与List转Datatable的相关文章

.Net多个DataTable合并,及过滤掉DataTable中重复数据行

DataTable dt01= new DataTable(); DataTable dt02= new DataTable(); DataTable dtRs = new DataTable(); dt01=sqlHelper.GetDataTable(strSQL001) dt02=sqlHelper.GetDataTable(strSQL002) //数据表dt02与dt01合并 dt01.Merge(dt02); //多个表合并可能产生重复数据,过滤掉重复数据 DataView dv =

“DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用

“DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用 造成这个错误的原因是,在使用DataTable操作Sql和Excel的时候发生了二义性. 解决办法:把命名空间写全了,如: System.Data.DataTable dt = null; "DataTable"是"System.Data.DataTable"和"Microsoft.

多个不同的表合并到一个datatable中,repeater在绑定datatable

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Data.SqlClient;namespace LZserverList{    public partial class LZList : System.Web.UI.

DataTable to CSV and CSV to DataTable

一.将DataTable内容写入到CSV文件 /// <summary>        /// 将DataTable中的数据保存成CSV文件        /// </summary>        private void btnSaveCSV_Click(object sender, EventArgs e)        {            saveFileDialog1.Filter = "CSV文件|*.CSV";            save

C# 直接创建一个DataTable,并为之添加数据(自定义DataTable) 转

DataTable dt=new DataTable("cart"); DataColumn dc1=new DataColumn("prizename",Type.GetType("System.String")); DataColumn dc2=new DataColumn("point",Type.GetType("System.Int16")); DataColumn dc3=new DataCol

C# 向DataTable中插入数据或伪造DataTable

方法一: DataTable  tblDatas = new DataTable("Datas"); DataColumn dc = null; dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32")); dc.AutoIncrement = true;//自动增加 dc.AutoIncrementSeed = 1;//起始为1 dc.AutoIncrementStep = 1;/

DataTable的列复制到另外DataTable

try { //获取满足条件的数据 DataTable Mdr = datable.Select("kday >='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' and kday <='" + DateTime.Now.AddMinutes(200).ToString("yyyy-MM-dd HH:mm:ss") + "' ").Co

EasyUI - Datatable转Json and Json转Datatable

using System; using System.Data; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Web.Script.Serialization; namespace *** { public class DatatableToJson { #region DataTable --> Json 字符串 /// <summary> ///

NPOI DataTable转Excel ,Excel转DataTable

DataTableToExcel: 1 public static void dataTableToExcel(DataTable table, string fileName) 2 { 3 using (MemoryStream ms = new MemoryStream()) 4 { 5 6 IWorkbook workbook = null; 7 8 if (fileName.IndexOf(".xlsx") > 0) 9 workbook = new XSSFWorkbo