c# .NET DataTable转换为List 反射
作者:互联网
public static List<T> ConvertToEx<T>(DataTable dt) where T : new() { if (dt == null) return null; if (dt.Rows.Count <= 0) return null; List<T> list = new List<T>(); Type type = typeof(T); PropertyInfo[] propertyInfos = type.GetProperties(); //获取泛型的属性 List<DataColumn> listColumns = dt.Columns.Cast<DataColumn>().ToList(); //获取数据集的表头,以便于匹配 T t; foreach (DataRow dr in dt.Rows) { t = new T(); foreach (PropertyInfo propertyInfo in propertyInfos) { try { DataColumn dColumn = listColumns.Find(name => name.ToString().ToUpper() == propertyInfo.Name.ToUpper()); //查看是否存在对应的列名 if (dColumn != null) { var uu = propertyInfo.PropertyType.Name; if (uu == "Int32") { if (dr[propertyInfo.Name].ToString() != "") { propertyInfo.SetValue(t, Convert.ToInt32(dr[propertyInfo.Name]), null); //赋值 } } else if (uu == "Boolean") { if (dr[propertyInfo.Name].ToString() != "") { propertyInfo.SetValue(t, Convert.ToBoolean(dr[propertyInfo.Name]), null); //赋值 } } else if (uu == "Decimal") { if (dr[propertyInfo.Name].ToString() != "") { propertyInfo.SetValue(t, Convert.ToDecimal(dr[propertyInfo.Name]), null); //赋值 } } else if (uu == "Double") { if (dr[propertyInfo.Name].ToString() != "") { propertyInfo.SetValue(t, Convert.ToDouble(dr[propertyInfo.Name]), null); //赋值 } } else { if (!string.IsNullOrEmpty(dr[propertyInfo.Name].ToString())) { propertyInfo.SetValue(t, dr[propertyInfo.Name], null); //赋值 } } } } catch (Exception ex) { throw new Exception(ex.Message); } } list.Add(t); } return list; }
标签:Name,c#,List,ToString,propertyInfo,NET,null,dr,dt 来源: https://www.cnblogs.com/wangxlei/p/15331803.html