• DataTable到范型转换


    /// <summary>
    /// 适合于实体类和DataTable对应的情况
    /// </summary>

    public class ConvertExtend
    {
        //将泛型类转换成DataTable
        public static DataTable ToDataTable<T>(List<T> entitys)
        {
            DataTable dtResult = new DataTable();
            if (entitys == null || entitys.Count < 1)
            {
                throw new Exception("需转换的集合为空");
            }
            Type entityType = entitys[0].GetType();
            List<PropertyInfo> propertyInfoList = entityType.GetProperties().ToList<PropertyInfo>();
            foreach (PropertyInfo item in propertyInfoList)
            {
                dtResult.Columns.Add(new DataColumn(item.Name, item.PropertyType));
            }
            foreach (T entity in entitys)
            {
                DataRow dr = dtResult.NewRow();
                foreach (PropertyInfo item in propertyInfoList)
                {
                    dr[item.Name] = item.GetValue(entity, null);
                }
                dtResult.Rows.Add(dr);
            }
            return dtResult;
        }
        //将泛型类转换成DataTable
        public static IList<T> ToList<T>(DataTable dt)
        {
            List<T> list = new List<T>();
            //T model = default(T);
            for (int iRow = 0; iRow < dt.Rows.Count; iRow++)
            {
                DataRow dr = dt.Rows[iRow];
                T t = (T)System.Activator.CreateInstance(typeof(T));
                List<PropertyInfo> listPropertyInfo = t.GetType().GetProperties().ToList<PropertyInfo>();
                foreach (PropertyInfo item in listPropertyInfo)
                {
                    if (dr[item.Name] != DBNull.Value)
                    {
                        item.SetValue(t, dr[item.Name], null);
                    }
                    else
                    {
                        item.SetValue(t, (string)null, null);
                    }
                }
                list.Add(t);
            }
            return list;
        }

    }

  • 相关阅读:
    STL特性总述——写在前面
    C++多线程框架
    C++内存管理之unique_ptr
    ubuntu文本模式/终端中文乱码解决
    log4net日志在app.config中assembly不起作用
    解决多线程委托二义性问题
    IIS 中文文件名下载会出现403访问被拒绝
    C# 异常:从作用域“”引用了“FiasHostApp.Entity.DBEntity.FIAS_RM_v1.ITraNetMgrUnitBaseInfoRecord”类型的变量“w”,但该变量未定义
    C# string.Split对于换行符的分隔正确用法
    knockoutJS+knockout.multimodels使用记录
  • 原文地址:https://www.cnblogs.com/single/p/1533367.html
Copyright © 2020-2023  润新知