C#中实现DataTable 与 List泛型集合 互转

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace LifeDecidesHappiness.Net.Utility.ListDataTable
{
    /// <summary>
    ///     https://www.cnblogs.com/LifeDecidesHappiness/p/15478850.html
    ///     C#中实现DataTable 与 List泛型集合 互转
    ///     LDH @ 2021-10-29
    /// </summary>
    public class DataTable2ListHelper
    {
        /// <summary>
        ///     DataTable转成List
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ToDataList<T>(DataTable dt)
        {
            var list = new List<T>();
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            foreach (DataRow item in dt.Rows)
            {
                var s = Activator.CreateInstance<T>();
                for (var i = 0; i < dt.Columns.Count; i++)
                {
                    var info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                    if (info != null)
                        try
                        {
                            if (!Convert.IsDBNull(item[i]))
                            {
                                object v;
                                if (info.PropertyType.ToString().Contains("System.Nullable"))
                                    v = Convert.ChangeType(item[i],
                                        Nullable.GetUnderlyingType(info.PropertyType) ??
                                        throw new InvalidOperationException());
                                else
                                    v = Convert.ChangeType(item[i], info.PropertyType);
                                info.SetValue(s, v, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("字段【" + info.Name + "'】转换出错," + ex.Message);
                        }
                }

                list.Add(s);
            }

            return list;
        }

        /// <summary>
        ///     DataTable转成Dto
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static T ToDataDto<T>(DataTable dt)
        {
            var s = Activator.CreateInstance<T>();
            if (dt == null || dt.Rows.Count == 0) return s;
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            for (var i = 0; i < dt.Columns.Count; i++)
            {
                var info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                if (info != null)
                    try
                    {
                        if (!Convert.IsDBNull(dt.Rows[0][i]))
                        {
                            object v;
                            if (info.PropertyType.ToString().Contains("System.Nullable"))
                                v = Convert.ChangeType(dt.Rows[0][i],
                                    Nullable.GetUnderlyingType(info.PropertyType) ??
                                    throw new InvalidOperationException());
                            else
                                v = Convert.ChangeType(dt.Rows[0][i], info.PropertyType);
                            info.SetValue(s, v, null);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("字段【" + info.Name + "'】转换出错," + ex.Message);
                    }
            }

            return s;
        }

        /// <summary>
        ///     将实体集合转换为DataTable
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="entities">实体集合</param>
        public static DataTable ToDataTable<T>(List<T> entities)
        {
            var result = CreateTable<T>();
            FillData(result, entities);
            return result;
        }

        /// <summary>
        ///     创建表
        /// </summary>
        private static DataTable CreateTable<T>()
        {
            var result = new DataTable();
            var type = typeof(T);
            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var propertyType = property.PropertyType;
                if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    propertyType = propertyType.GetGenericArguments()[0];
                result.Columns.Add(property.Name, propertyType);
            }

            return result;
        }

        /// <summary>
        ///     填充数据
        /// </summary>
        private static void FillData<T>(DataTable dt, IEnumerable<T> entities)
        {
            foreach (var entity in entities) dt.Rows.Add(CreateRow(dt, entity));
        }

        /// <summary>
        ///     创建行
        /// </summary>
        private static DataRow CreateRow<T>(DataTable dt, T entity)
        {
            var row = dt.NewRow();
            var type = typeof(T);
            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                row[property.Name] = property.GetValue(entity) ?? DBNull.Value;
            return row;
        }
    }
}
踏实做一个为人民服务的搬运工!
原文地址:https://www.cnblogs.com/LifeDecidesHappiness/p/15478850.html