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

作者最新文章
Winform TextBox (文本框) 密码输入框, 输入内容显示*号 (星号)
Winform 启动前弹出登录界面, 登录成功之后再显示主界面
C# 字符串string和字符数组char[]的相互转换
C# 字符串倒序输出, 实现字符串倒序的方法
Winform 如何从 TextBox(文本框) 控件读取每一行数据到数组