using Mesnac.Action.ChemicalWeighing; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Mesnac.Action.ChemicalWeighing { public static class DataTableHelper { #region DataTable 转换成泛型List /// /// DataTable 转换成泛型List /// /// 实体对象类 /// 数据DatatTable /// List集合 /// 空字符是否需要 /// List<实体对象> public static List DataTableToList(this DataTable dt, List objList = null, bool isNullEmpty = true) { if (dt == null) { objList = null; } if (objList == null) { objList = new List(); } var columnNames = dt.Columns.Cast().Select(c => c.ColumnName).ToList(); var properties = typeof(Hw_WareHouseSubView).GetProperties(); object value = null; foreach (DataRow row in dt.Rows) { var t = Activator.CreateInstance(); { foreach (PropertyInfo pro in properties) { if (!pro.CanWrite) { continue; } if (dt.Columns.Contains(pro.Name.ToUpper())) { value = row[pro.Name]; if (value is System.DBNull) { value = null; if (pro.PropertyType.FullName == "System.String") { value = string.Empty; } } if (isNullEmpty) { if (pro.PropertyType.FullName == "System.String" && string.IsNullOrEmpty(value.ToString().Trim())) { value = string.Empty; } } if (pro.PropertyType.IsGenericType && pro.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) && value != null) { pro.SetValue(t, Convert.ChangeType(value, Nullable.GetUnderlyingType(pro.PropertyType)), null); } else if (pro.PropertyType.IsEnum) { pro.SetValue(t, Convert.ChangeType(value, Enum.GetUnderlyingType(pro.PropertyType)), null); } else { pro.SetValue(t, value, null); } } } } objList.Add(t); } return objList; } #endregion } }