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

        
            public static List<T> DatatTable_ToList<T>(DataTable dt) where T : class, new()
            {
                int a = 0;
                int b = 0;
                try
                {
                    List<T> ts = new List<T>();
    
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        // 获得此模型的类型  
                        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;
                                // 检查DataTable是否包含此列  
                                if (dt.Columns.Contains(tempName))
                                {
                                    // 判断此属性是否有Setter  
                                    if (!pi.CanWrite)
                                        continue;
                                    object value = dr[tempName];
                                    if (value != DBNull.Value)
                                    {
                                        //pi.SetValue(t, value, null);  
                                        // pi.SetValue(t, Convert.ChangeType(value, pi.PropertyType, CultureInfo.CurrentCulture), null);
                                        pi.SetValue(t, ChanageType(value, pi.PropertyType), null);
                                    }
                                }
                            }
                            ts.Add(t);
                        }
                    }
    
                    return ts;
                }
                catch (Exception ex)
                {
                    string aa = a.ToString();
                    string bb = b.ToString();
                    throw;
                }
            }
     
  • 相关阅读:
    css清除浮动
    对象遍历
    vue 小工具
    数据库优化-聚合索引
    mysql修改唯一索引
    输出带pre的调试信息
    mysql的group by优化跟limit优化
    地址联动数据抓取
    php7新特新
    linux同步系统时间
  • 原文地址:https://www.cnblogs.com/weixin18/p/15254079.html
Copyright © 2011-2022 走看看