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;
                }
            }
     
  • 相关阅读:
    linq.js
    ES6入门
    Visual Studio Code之常备快捷键
    JavaScript——数组
    谈程序员的出路
    优秀博文
    多媒体封装格式详解---MP4
    音视频文件分析工具
    offsetof(s,m)解析
    GCC 提供的原子操作
  • 原文地址:https://www.cnblogs.com/weixin18/p/15254079.html
Copyright © 2011-2022 走看看