C# DataTable 转换 Model实体类,DataTable 转换 List<>集合

C# DataTable 转换 Model实体类,DataTable 转换 List<>集合
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个新的DataTable
            DataTable dt = new DataTable("User");
            dt.Columns.Add("UserName", typeof(string));
            dt.Columns.Add("Password", typeof(string));
            dt.Columns.Add("Age", typeof(int));

            for (int i = 0; i < 5; ++i)
            {
                DataRow dr = dt.NewRow();
                dr["UserName"] = "用户名" + i.ToString();
                dr["Password"] = "密码" + i.ToString();
                dr["Age"] = 20;
                dt.Rows.Add(dr);

                // DataTable 转换为实体
                User user = DataTableToModel<User>(dt);
            }

            // DataTable 转换为List
            List<User> users = DataTableToList<User>(dt);
        }

        /// <summary>
        /// DataTable -> Model
        /// </summary>
        /// <typeparam name="T">数据项</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static T DataTableToModel<T>(DataTable dt) where T : new()
        {
            try
            {
                if (dt == null || dt.Rows.Count == 0)
                {
                    return default(T);
                }

                T t = new T();
                // 获取行数据
                DataRow dr = dt.Rows[0];
                // 获取栏目
                DataColumnCollection columns = dt.Columns;
                // 获得此模型的公共属性
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    string name = pi.Name;
                    // 检查DataTable是否包含此列    
                    if (columns.Contains(name))
                    {
                        if (!pi.CanWrite) continue;

                        object value = dr[name];
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(t, value, null);
                        }
                    }
                }
                return t;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// DataTable -> List
        /// </summary>
        /// <typeparam name="T">数据项</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : new()
        {
            try
            {
                if (dt == null || dt.Rows.Count == 0)
                {
                    return new List<T>();
                }

                // 定义集合
                List<T> list = new List<T>();

                // 获取栏目
                DataColumnCollection columns = dt.Columns;
                foreach (DataRow dr in dt.Rows)
                {
                    T t = new T();
                    // 获得此模型的公共属性
                    PropertyInfo[] propertys = t.GetType().GetProperties();
                    foreach (PropertyInfo pi in propertys)
                    {
                        string name = pi.Name;
                        // 检查DataTable是否包含此列    
                        if (columns.Contains(name))
                        {
                            if (!pi.CanWrite) continue;

                            object value = dr[name];
                            if (value != DBNull.Value)
                            {
                                pi.SetValue(t, value, null);
                            }
                        }
                    }
                    list.Add(t);
                }
                return list;
            }
            catch
            {
                throw;
            }
        }
    }

    /// <summary>
    /// 用户
    /// </summary>
    public class User
    {
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
    }
}

作者最新文章
C# 使用 CSVHelper 操作 csv 文件, .net core, .net framework 读取写入 csv 文件
C# 实现字符串文本换行的方法,文本如何换行
C# 如何循环读取文件每一行文本内容
C# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角