通过反射和泛型实现DataTable转Object

实现DataTable转为对象
/// <summary>
        /// 转换DataTable为指定类型的list对象
        /// </summary>
        /// <typeparam name="T">指定的转换类型</typeparam>
        /// <param name="dt">需要转换的DataTable</param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : class, new()
        {
            var list = new List<T>();
            if (dt.Rows.Count > 0)
            {
                var propertyInfoes = typeof(T).GetProperties();
                foreach (DataRow dataRow in dt.Rows)
                {
                    var t = new T();
                    foreach (var propertyInfo in propertyInfoes)
                    {
                        var tempName = propertyInfo.Name;
                        if (dt.Columns.Contains(tempName))
                        {
                            if (!propertyInfo.CanWrite) continue;
                            object value = dataRow[tempName];
                            if (value != DBNull.Value)
                            {
                                propertyInfo.SetValue(t, value);
                            }
                        }
                    }
                    list.Add(t);
                }
            }

            return list;
        }

        public static T DataTableToModel<T>(DataTable dt) where T : class, new()
        {
            if (dt.Rows.Count <= 0)
            {
                return default(T);
            }
            else
            {
                var t = new T();
                var propertyInfoes = typeof(T).GetProperties();
                foreach (var propertyInfo in propertyInfoes)
                {
                    var tempName = propertyInfo.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!propertyInfo.CanWrite) continue;
                        object value = dt.Rows[0][tempName];
                        if (value != DBNull.Value)
                        {
                            propertyInfo.SetValue(t, value);
                        }
                    }
                }

                return t;
            }
        }
    }
原文地址:https://www.cnblogs.com/prayol/p/8507961.html