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

           注意table 列的参数类型,若不为string 需要详细声明 如 typeof(Int32) 
            public static IList<T> ConvertTo<T>(DataTable dt) where T : new()
            {
                IList<T> list = new List<T>();
                if (dt == null || dt.Rows.Count <= 0)
                {
                    return null;
                }  
                Type type = typeof(T);
                PropertyInfo[] propertys = type.GetProperties();//获取T的所有属性
                try
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        T t = new T();
                        foreach (PropertyInfo pi in propertys)
                        {  
                            if (dt.Columns.Contains(pi.Name))
                            {    
                                if (!pi.CanWrite) continue;
                                object value = dr[pi.Name];
                                if (value != DBNull.Value)
                                    pi.SetValue(t, value, null);
                            }
                        }
                        list.Add(t);
                    }
                }
                catch (Exception ex)
                {
                    list = null;
                }
                return list;
            }
  • 相关阅读:
    android的FATAL EXCEPTION: main错误
    ORA12560: TNS: 协议适配器错误
    BroadcastReceiver应用详解
    using C# 详解
    mysqlproxy0.8版本读写分离测试总结
    Mysql SHOW PROCESSLIST Sending data
    [转载]大型网站运维探讨和心得
    找出并optimization表
    mysql中普通索引和唯一索引的效率对比
    ps aux 中STAT 解释
  • 原文地址:https://www.cnblogs.com/cherious/p/11061973.html
Copyright © 2011-2022 走看看