zoukankan      html  css  js  c++  java
  • DataTable转List

     public class ModelConvertHelper<T> where T : new()  // 此处一定要加上new()
            {
    
                public static List<T> ConvertToModel(DataTable dt)
                {
    
                    List<T> ts = new List<T>();// 定义集合
                    Type type = typeof(T); // 获得此模型的类型
                    string tempName = "";
                    foreach (DataRow dr in dt.Rows)
                    {
                        T t = new T();
                        PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                        foreach (PropertyInfo pi in propertys)
                        {
                            tempName = pi.Name;
                            if (dt.Columns.Contains(tempName))
                            {
                                if (!pi.CanWrite) continue;
                                object value = dr[tempName];
                                if (value != DBNull.Value)
                                    pi.SetValue(t, value, null);
                            }
                        }
                        ts.Add(t);
                    }
                    return ts;
                }
            }
    调用方法为: List<NewsInfo> list = ModelConvertHelper<NewsInfo>.ConvertToModel(da);

      

  • 相关阅读:
    迭代器简介
    关于判断对象是否相等的问题
    NIO
    BIO流分类介绍
    servlet简介
    http协议简介
    爬虫常用链接
    http和https协议
    爬虫的合法性研究
    爬虫介绍
  • 原文地址:https://www.cnblogs.com/qzxj/p/5417983.html
Copyright © 2011-2022 走看看