• C# DataTable和List转换操作类


    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Com.AppCode.Extend
    {
        static public class TableConvert
        {
            #region DataTable 1
            /// <summary>
            /// 将datatable转换为泛型集合
            /// </summary>
            /// <typeparam name="TEntity"></typeparam>
            /// <param name="inputDataTable"></param>
            /// <returns></returns>
            public static List<TEntity> ToList<TEntity>(this DataTable inputDataTable) where TEntity : class, new()
            {
                if (inputDataTable == null)
                {
                    throw new ArgumentNullException("input datatable is null");
                }
                Type type = typeof(TEntity);
                PropertyInfo[] propertyInfos = type.GetProperties();
                List<TEntity> lstEntitys = new List<TEntity>();
                foreach (DataRow row in inputDataTable.Rows)
                {
                    object obj = Activator.CreateInstance(type);
                    foreach (PropertyInfo pro in propertyInfos)
                    {
                        foreach (DataColumn col in inputDataTable.Columns)
                        {
                            //如果直接查询的数据库,数据库是不区别大小写的,所以转换为小写忽略大小写的问题
                            if (col.ColumnName.ToLower().Equals(pro.Name.ToLower()))
                            {
                                //属性是否是可写的,如果是只读的属性跳过。
                                if (pro.CanWrite)
                                {
                                    //判断类型,基本类型,如果是其他的类属性
                                    if (pro.PropertyType == typeof(System.Int32))
                                    {
                                        pro.SetValue(obj, Convert.ToInt32(row[pro.Name.ToLower()]));
                                    }
                                    else if (pro.PropertyType == typeof(System.String))
                                    {
                                        pro.SetValue(obj, row[pro.Name.ToLower()].ToString());
                                    }
                                    else if (pro.PropertyType == typeof(System.Boolean))
                                    {
                                        pro.SetValue(obj, Convert.ToBoolean(row[pro.Name.ToLower()]));
                                    }
                                    else if (pro.PropertyType == typeof(System.DateTime))
                                    {
                                        pro.SetValue(obj, Convert.ToDateTime(row[pro.Name.ToLower()]));
                                    }
                                    else if (pro.PropertyType == typeof(System.Int64))
                                    {
                                        pro.SetValue(obj, Convert.ToInt64(row[pro.Name.ToLower()]));
                                    }
                                    else
                                    {
                                        pro.SetValue(obj, row[pro.Name.ToLower()]);
                                    }
    
                                }
                            }
                        }
                    }
                    TEntity tEntity = obj as TEntity;
                    lstEntitys.Add(tEntity);
                }
                return lstEntitys;
            }
            /// <summary>
            /// 将list转换为datatable
            /// </summary>
            /// <typeparam name="TEntity"></typeparam>
            /// <param name="inputList"></param>
            /// <returns></returns>
            public static DataTable ToDataTable<TEntity>(this List<TEntity> inputList) where TEntity : class, new()
            {
                if (inputList == null)
                {
                    throw new ArgumentNullException("inputList");
                }
                DataTable dt = null;
                Type type = typeof(TEntity);
                if (inputList.Count == 0)
                {
                    dt = new DataTable(type.Name);
                    return dt;
                }
                else { dt = new DataTable(); }
                PropertyInfo[] propertyInfos = type.GetProperties();
                foreach (var item in propertyInfos)
                {
                    dt.Columns.Add(new DataColumn() { ColumnName = item.Name, DataType = item.PropertyType });
                }
                foreach (var item in inputList)
                {
                    DataRow row = dt.NewRow();
                    foreach (var pro in propertyInfos)
                    {
                        row[pro.Name] = pro.GetValue(item);
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }
            #endregion
    
            #region DataTable 2
    
            /// <summary>
            /// DataTable转成List
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static List<T> ToDataList<T>(this DataTable dt)
            {
                var list = new List<T>();
                var plist = new List<PropertyInfo>(typeof(T).GetProperties());
                foreach (DataRow item in dt.Rows)
                {
                    T s = Activator.CreateInstance<T>();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                        if (info != null)
                        {
                            try
                            {
                                if (!Convert.IsDBNull(item[i]))
                                {
                                    object v = null;
                                    if (info.PropertyType.ToString().Contains("System.Nullable"))
                                    {
                                        v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
                                    }
                                    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>(this DataTable dt)
            {
                T s = Activator.CreateInstance<T>();
                if (dt == null || dt.Rows.Count == 0)
                {
                    return s;
                }
                var plist = new List<PropertyInfo>(typeof(T).GetProperties());
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
                    if (info != null)
                    {
                        try
                        {
                            if (!Convert.IsDBNull(dt.Rows[0][i]))
                            {
                                object v = null;
                                if (info.PropertyType.ToString().Contains("System.Nullable"))
                                {
                                    v = Convert.ChangeType(dt.Rows[0][i], Nullable.GetUnderlyingType(info.PropertyType));
                                }
                                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 ToTable<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(System.Reflection.BindingFlags.Public | System.Reflection.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)
            {
                DataRow row = dt.NewRow();
                var type = typeof(T);
                foreach (var property in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
                {
                    row[property.Name] = property.GetValue(entity) ?? DBNull.Value;
                }
                return row;
            }
    
            #endregion
    
            #region DataTable 3
            /// <summary>
            /// DataTable转换为List
            /// </summary>
            /// <typeparam name="T">实体对象</typeparam>
            /// <param name="dt">datatable表</param>
            /// <returns>返回list集合</returns>
    
            static public List<T> TableToList<T>(DataTable dt) where T : new()
            {
                //定义集合
                List<T> list = new List<T>();
                //获得此模型的类型
                Type type = typeof(T);
                //定义一个临时变量
                string tempName = string.Empty;
                //遍历Datatable中所有的数据行
                foreach (DataRow dr in dt.Rows)
                {
                    T t = new T();
                    //获得此模型的公共属性
                    PropertyInfo[] propertys = t.GetType().GetProperties();
                    //遍历该对象的所有属性
                    foreach (PropertyInfo pi in propertys)
                    {
                        //将属性名称赋值给临时变量
                        tempName = pi.Name;
                        //检查DataTable是否包含此列(列名==对象的属性名)
                        if (dt.Columns.Contains(tempName))
                        {
                            //判断此属性是否有Setter
                            if (!pi.CanWrite) continue;//该属性不可写,直接跳出
                            //取值
                            object value = dr[tempName];
                            //如果非空,则赋给对象的属性
                            if (value != DBNull.Value)
                            {
                                //加一重if判断,如果属性值是int32类型的,就进行一次强制转换
                                if (pi.GetMethod.ReturnParameter.ParameterType.Name == "Int32")
                                {
                                    value = Convert.ToInt32(value);
                                }
                                pi.SetValue(t, value, null);
                            }
    
                        }
                    }
                    //对象添加到泛型集合中
                    list.Add(t);
                }
                return list;
            }
            #endregion
        }
    }
  • 相关阅读:
    从头认识java-14.2 进一步了解数组
    移植MonkeyRunner的图片对照和获取子图功能的实现-UiAutomator/Robotium篇
    JVM —— 移除永久代
    三层架构与四大天王之——查
    unity3D中使用Socket进行数据通信(一)
    npm使用指南
    java命令模式
    共享内存通讯编程
    jade 入门
    MongoDB数据库进阶 --- 增删查改...
  • 原文地址:https://www.cnblogs.com/hofmann/p/11765907.html
Copyright © 2020-2023  润新知