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;
            }
  • 相关阅读:
    新浪SAE搭建项目
    PHP ReflectionClass
    自定义时间函数
    mysql 日期函数
    jquery之商城菜单
    jquery之行自加自减
    前端之拖动面板
    商城轮播图
    js之返回网页顶部
    js之搜索框
  • 原文地址:https://www.cnblogs.com/cherious/p/11061973.html
Copyright © 2011-2022 走看看