代码越写越灵活,分享越分享越快乐
DataTable转List 泛型集合扩展方法分享
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.ComponentModel.DataAnnotations; using System.Runtime.CompilerServices; using System.Data; namespace System { /// <summary> /// table转list /// </summary> public static class DataTableExtend { public static List<T> ToList<T>(this DataTable dt) where T : class,new() { var list = new List<T>(); Type type = typeof(T).GetType(); for (int i = 0; i < dt.Rows.Count; i++) { T model = new T(); var dr = dt.Rows[i]; //字段集合 PropertyInfo[] listPro = model.GetType().GetProperties().Where(item=>item.IsDefined(typeof(InternalAttribute),false)).ToArray(); for (int j = 0; j < listPro.Length; j++) { var pi = listPro[i]; var columnName = pi.Name;//字段 var columnType = pi.PropertyType;//字段类型 Type underlyingType = Nullable.GetUnderlyingType(columnType); if (dt.Columns.Contains(columnName)) { if (!pi.CanWrite) continue; object value = dr[columnName]; if (value == DBNull.Value) continue; if (pi.PropertyType == typeof(string)) pi.SetValue(model, value.ToString(), null); else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?)) pi.SetValue(model, Convert.ToInt32(value), null); else if (pi.PropertyType == typeof(DateTime) || pi.PropertyType == typeof(DateTime?)) pi.SetValue(model, Convert.ToDateTime(value), null); else if (pi.PropertyType == typeof(float)) pi.SetValue(model, Convert.ToSingle(value), null); else if (pi.PropertyType == typeof(decimal)) pi.SetValue(model, Convert.ToDecimal(value), null); else if (pi.PropertyType == typeof(double)) pi.SetValue(model, Convert.ToDouble(value), null); else if ((underlyingType ?? columnType).IsEnum) {//判断枚举属性为空的属性赋值 if (underlyingType != null && !string.IsNullOrEmpty(value.ToString())) pi.SetValue(model, Enum.Parse(underlyingType ?? type, value.ToString()), null); else if (underlyingType == null && !string.IsNullOrEmpty(value.ToString())) pi.SetValue(model, Convert.ToInt32(value), null); else pi.SetValue(model, -1, null); } else pi.SetValue(model, value, null); } } list.Add(model); } return list; } } }
table转list 字段转属性的时候支持枚举属性类型
原文:https://www.cnblogs.com/axinno1/p/12896202.html