C# Model实体类 转换 DataTable,List<>集合 转换 DataTable, 字段类型可以是Nullable<>

C# Model实体类 转换 DataTable,List<>集合 转换 DataTable, 字段类型可以是Nullable<>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            User user = new User();
            user.UserName = "用户名";
            user.Password = "密码";
            user.Age = 20;

            List<User> users = new List<User>();
            for (int i = 0; i < 5; ++i)
            {
                user = new User();
                user.UserName = "用户名" + i.ToString();
                user.Password = "密码" + i.ToString();
                user.Age = 20;

                users.Add(user);
            }

            // Model -> DataTable
            DataTable dt1 = ModelToDataTable<User>(user);

            // List<> -> DataTable
            DataTable dt2 = ListToDataTable<User>(users);
        }


        /// <summary>
        /// Model -> DataTable
        /// </summary>
        /// <typeparam name="T">数据项</typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static DataTable ModelToDataTable<T>(T data)
        {
            try
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
                DataTable dt = new DataTable();

                // 创建栏
                for (int i = 0; i < properties.Count; i++)
                {
                    PropertyDescriptor property = properties[i];
                    // dt.Columns.Add(property.Name, property.PropertyType);
                    // 当字段类型是Nullable<>时
                    Type type = property.PropertyType;
                    if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {
                        type = type.GetGenericArguments()[0];
                    }
                    dt.Columns.Add(new DataColumn(property.Name, type));
                }
                object[] values = new object[properties.Count];

                // 赋值
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(data);
                }
                dt.Rows.Add(values);

                return dt;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// List -> DataTable
        /// </summary>
        /// <typeparam name="T">数据项</typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(IList<T> list)
        {
            try
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
                DataTable dt = new DataTable();

                // 创建栏
                for (int i = 0; i < properties.Count; i++)
                {
                    PropertyDescriptor property = properties[i];
                    // dt.Columns.Add(property.Name, property.PropertyType);
                    // 当字段类型是Nullable<>时
                    Type type = property.PropertyType;
                    if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {
                        type = type.GetGenericArguments()[0];
                    }
                    dt.Columns.Add(new DataColumn(property.Name, type));
                }
                object[] values = new object[properties.Count];

                // 赋值
                foreach (T item in list)
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = properties[i].GetValue(item);
                    }
                    dt.Rows.Add(values);
                }

                return dt;
            }
            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(文本框) 控件读取每一行数据到数组