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;
            }
  • 相关阅读:
    (ZOJ 3329) One Person Game (概率DP)
    python爬虫之json数据处理
    1034 Head of a Gang 图的遍历,map使用
    1030 Travel Plan Dijkstra+dfs
    vs C++ scanf 不安全
    1021. Deepest Root DFS 求最长无环路径
    1013. Battle Over Cities 用dfs计算联通分量
    无法解析的外部符号
    PAT DFS,BFS,Dijkstra 题号
    1004 Counting Leaves 对于树的存储方式的回顾
  • 原文地址:https://www.cnblogs.com/cherious/p/11061973.html
Copyright © 2011-2022 走看看