zoukankan      html  css  js  c++  java
  • DataTable 转为List<T>集合

    public static List<T> HubbleTableToList<T>(this DataTable dt) where T:Class
    {
    List<T> _list = new List<T>();
    if (dt == null) return _list;
    T model;
    foreach (DataRow dr in dt.Rows)//进行循环dataTable行数据
    {
    model = Activator.CreateInstance<T>();//获取泛型类型的新实例
    foreach (DataColumn dc in dr.Table.Columns)//循环该行的列
    {
    object drValue = dr[dc.ColumnName];//根据列名获取行数据
    PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);//model.GetType()表示获取model的类型,GetProperty()获取指定名称的公共属性,其中需要引用using System.Reflection;
    if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
    {
    if (pi.PropertyType == typeof(int)||pi.PropertyType==typeof(int?))//注:如果未加此判断,则会出现 类型“System.Int64”的对象无法转换为类型“System.Int32”。的错误
    {
    drValue = Convert.ToInt32(drValue);
    }
    pi.SetValue(model, drValue, null);
    }
    }
     
    _list.Add(model);
     
    }
    return _list;
    }
  • 相关阅读:
    es6 简介
    npm 快速开发技巧
    css清除浮动方法
    mui 总结
    7种 JS 创建对象的经典方式
    JavaScript 的 this 原理
    使用定时器
    dom 操作及方法
    JavaScript的6种继承方式及其优缺点
    贪吃蛇游戏代码
  • 原文地址:https://www.cnblogs.com/97310ZT/p/8580682.html
Copyright © 2011-2022 走看看