DataTable转List<T>

/// <summary>
    /// DataTable转List<T>
    /// </summary>
    public static class TableToList<T> where T : new()
    {
        public static List<T> ConvertToList(DataTable dt)
        {
            List<T> list = new List<T>();
            // 获得此模型的类型  
            Type type = typeof(T);
            string temp = string.Empty;

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                
                PropertyInfo[] propertys = t.GetType().GetProperties();//反射
                
                foreach (PropertyInfo pi in propertys)
                {
                    temp = pi.Name;//将属性名称赋值给临时变量  
                    //检查DataTable是否包含此列(列名==对象的属性名)    
                    if (dt.Columns.Contains(temp))
                    {
                        // 判断此属性是否有Setter  
                        if (!pi.CanWrite) continue;//该属性不可写,直接跳出  
                        //取值  
                        object value = dr[temp];
                        //如果非空,则赋给对象的属性  
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                //对象添加到泛型集合中  
                list.Add(t);
            }
            return list;
        }
    }

调用:TableToList<对象>.ConvertToList(dt);

posted @ 2015-04-30 16:08  ♀影☆响  阅读(235)  评论(3编辑  收藏  举报