码迷,mamicode.com
首页 > 其他好文 > 详细

实体对象,List泛型 转换为DataTable

时间:2014-09-18 13:13:13      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:os   ar   for   sp   on   c   ad   new   r   

 

        /// <summary>
        /// 实体对象转换DataTable
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>DataTable</returns>
        public static DataTable GetDataTableByEntity(object entity)
        {
            DataTable dt = new DataTable();
            Type type = entity.GetType();
            dt.TableName = type.Name;
            DataRow dr = dt.NewRow();
            foreach (var p in type.GetProperties())
            {
                if (!dt.Columns.Contains(p.Name))
                    dt.Columns.Add(p.Name);
                dr[p.Name] = p.GetValue(entity, null) == null ? "" : p.GetValue(entity, null).ToString();
            }
            dt.Rows.Add(dr);
            return dt;
        }

        /// <summary>
        /// List转换成DataTable
        /// </summary>
        /// <typeparam name="T">实体对象类型</typeparam>
        /// <param name="list">list集合</param>
        /// <returns>DataTable</returns>
        public static DataTable GetDataTableByList<T>(List<T> list)
        {
            DataTable dt = new DataTable();
            foreach (T t in list)
            {
                DataRow dr = dt.NewRow();
                Type type = t.GetType();
                if (String.IsNullOrEmpty(dt.TableName))
                    dt.TableName = type.Name;
                foreach (var p in type.GetProperties())
                {
                    if (!dt.Columns.Contains(p.Name))
                        dt.Columns.Add(p.Name);
                    dr[p.Name] = p.GetValue(t, null) == null ? "" : p.GetValue(t, null).ToString();
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

 

实体对象,List泛型 转换为DataTable

标签:os   ar   for   sp   on   c   ad   new   r   

原文地址:http://www.cnblogs.com/yf2011/p/3978983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!