欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DataTable与实体类的转换

程序员文章站 2022-06-15 09:47:35
...

一、实现DataTable与实体类转换

/***
*	Title:"数据采集" 项目
*		主题:表和实体帮助类
*	Description:
*		功能:
*		    1、DataTable指定行数据转化为实体类
*		    2、DataTable所有数据转换成实体类列表
*		    3、实体类列表转换成DataTable
*	Date:2021
*	Version:0.1版本
*	Author:Coffee
*	Modify Recoder:
*/

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    class TableToEntityHelper
    {
        /// <summary>
        /// DataTable指定行数据转化为实体类
        /// </summary>
        /// <typeparam name="T">实体类</typeparam>
        /// <param name="dataTable">dataTable</param>
        /// <param name="rowIndex">需要解析行的索引</param>
        /// <returns>返回当前指定行的实体类数据</returns>
        public static T DataTableToEntity<T>(DataTable dataTable,int rowIndex) where T : new()
        {
            try
            {
                if (dataTable == null || dataTable.Rows.Count <= 0 || rowIndex<0)
                {
                    return default(T);
                }

                //实例化实体类
                T t = new T();
                // 获取指定行数据
                DataRow dr = dataTable.Rows[rowIndex];
                // 获取所有列
                DataColumnCollection columns = dataTable.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 (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// DataTable所有数据转换成实体类列表
        /// </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 p in propertys)
                    {
                        string name = p.Name;
                        // 检查DataTable是否包含此列    
                        if (columns.Contains(name))
                        {
                            if (!p.CanWrite) continue;

                            object value = dr[name];

                            if (value != DBNull.Value)
                            {
                                是否需要转化
                                //if (value is int || value is float || value is decimal || value is double)
                                //{
                                //    p.SetValue(t, value.ToString(), null);
                                //}
                                //else
                                //{
                                //    p.SetValue(t, value, null);
                                //}

                                p.SetValue(t, value, null);
                            }
                        }
                    }
                    list.Add(t);
                }
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 实体类列表转换成DataTable
        /// </summary>
        /// <param name="entityList">实体类列表</param>
        /// <param name="excludeFields">排除字段</param>
        /// <returns>返回实体类列表对应的DataTable</returns>
        public static DataTable ListToDataTable<T>(List<T> entityList, List<string> excludeFields = null)
        {
            var countExclude = 0;
            if (excludeFields != null)
                countExclude = excludeFields.Count();

            //检查实体集合不能为空
            if (entityList == null || entityList.Count <= 0)
            {
                throw new Exception("需转换的集合为空");
            }

            //取出第一个实体的所有属性
            Type entityType = entityList[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();



            //实例化DataTable
            DataTable dt = new DataTable();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                Type colType = entityProperties[i].PropertyType;
                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {
                    colType = colType.GetGenericArguments()[0];
                }
                //排除列
                string fieldName = entityProperties[i].Name;
                if (excludeFields == null || !excludeFields.Contains(fieldName))
                {
                    dt.Columns.Add(fieldName, colType);
                }
            }

            //将所有entity添加到DataTable中
            foreach (object entity in entityList)
            {
                //检查所有的的实体都为同一类型
                if (entity.GetType() != entityType)
                {
                    throw new Exception("要转换的集合元素类型不一致");
                }
                object[] entityValues = new object[dt.Columns.Count];
                int icount = 0;
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    //排除列
                    string fieldName = entityProperties[i].Name;
                    if (excludeFields == null || !excludeFields.Contains(fieldName))
                    {
                        entityValues[i - icount] = entityProperties[i].GetValue(entity, null);
                    }
                    else
                    {
                        icount++;
                    }
                }
                dt.Rows.Add(entityValues);
            }

            return dt;
        }


    }//Class_end

}

二、使用方法

            //DataTable指定行数据转化为实体类
            //获取到当前选中的所有行
            int[] rows = gridView1.GetSelectedRows();
            if (rows!=null && rows.Length>0)
            {
                //DataTable指定行数据转化为实体类
                PeopleInfo peopleInfo = TableToEntityHelper.DataTableToEntity<PeopleInfo>(_dataTable, rows[0]);
            }
           

            //DataTable转换成实体类列表
            List<PeopleInfo> peopleInfos = TableToEntityHelper.DataTableToList<PeopleInfo>(_dataTable);



            //需要排除的类字段
            List<string> execlude = new List<string>()
            {
               "ID","Sex"
            };
            //实体类列表转换成DataTable
            DataTable dt = TableToEntityHelper.ListToDataTable(GetPeopeoInfos(),execlude);
            //DataTable转换成实体类列表(用于查看效果)
            List<PeopleInfo> peopleInfos2 = TableToEntityHelper.DataTableToList<PeopleInfo>(dt);





  //模拟一个人员数据列表
        private List<PeopleInfo> GetPeopeoInfos()
        {
            List<PeopleInfo> peopeoInfos = new List<PeopleInfo>()
            {
                new PeopleInfo{ ID="JK001",FullName="杨万里",Sex="男",IdCard="523033199001026780"},
                new PeopleInfo{ ID="JK002",FullName="杨新宇",Sex="男",IdCard="523033199001026781"},
                new PeopleInfo{ ID="JK003",FullName="钟一明",Sex="男",IdCard="523033199001026782"},
                new PeopleInfo{ ID="JK004",FullName="张艺上",Sex="男",IdCard="523033199001026783"},
                new PeopleInfo{ ID="JK004",FullName=" ",Sex="男",IdCard="523033199001026784"},
                new PeopleInfo{ ID="JK006",FullName="胡一统",Sex="男",IdCard="523033199001026785"},
                new PeopleInfo{ ID="JK007",FullName="马国富",Sex="男",IdCard="523033199001026786"},
                new PeopleInfo{ ID="JK008",FullName="李宝军",Sex="男",IdCard="523033199001026787"},
                new PeopleInfo{ ID="JK009",FullName="软文策",Sex="男",IdCard="523033199001026788"},
            };

 
            return peopeoInfos;
        }


       //人员信息模型类
        private class PeopleInfo
        {
            public string ID { get; set; }
            public string FullName { get; set; }
            public string Sex { get; set; }
            public string IdCard { get; set; }
        }