首页 > 其他 > 详细

datatable to list 方法转换

时间:2015-06-19 10:05:49      阅读:175      评论:0      收藏:0      [点我收藏+]
#region 实体转换

        /// <summary>
        /// add extension method for datable
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static IList<TEntity> ToList<TEntity>(this DataTable dt) where TEntity : class ,new() {
            return ConvertToModel<TEntity>(dt);
        }
        public static IList<TEntity> ConvertToModel<TEntity>(DataTable dt) where TEntity : class ,new() {
            // 定义集合    
            IList<TEntity> ts = new List<TEntity>();

            // 获得此模型的类型   
            Type type = typeof(T);
            string tempName = "";

            foreach (DataRow dr in dt.Rows) {
                TEntity t = new TEntity();
                // 获得此模型的公共属性      
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys) {
                    tempName = pi.Name;  // 检查DataTable是否包含此列    

                    if (dt.Columns.Contains(tempName)) {
                        // 判断此属性是否有Setter      
                        if (!pi.CanWrite) continue;

                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }

        #endregion

 

datatable to list 方法转换

原文:http://www.cnblogs.com/hualiu0/p/4587705.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!