用DataTable填充实体类List
/// <summary> /// 用DataTable填充实体类List /// </summary> public static List<T> FillListModel<T>(DataTable dt) where T : new() { if (dt == null || dt.Rows.Count == 0) { return null; } List<T> modelList = new List<T>(); foreach (DataRow dr in dt.Rows) { //T model = (T)Activator.CreateInstance(typeof(T)); T model = new T(); for (int i = 0; i < dr.Table.Columns.Count; i++) { PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName); if (propertyInfo != null && dr[i] != DBNull.Value) propertyInfo.SetValue(model, dr[i], null); } modelList.Add(model); } return modelList; } /// <summary> /// 用DataTable填充实体类取DataTable中的第一条数据 /// </summary> public static T FillModel<T>(DataTable dt) where T : new() { if (dt == null || dt.Rows.Count == 0) { return default(T); } DataRow dr = dt.Rows[0]; //T model = (T)Activator.CreateInstance(typeof(T)); T model = new T(); for (int i = 0; i < dr.Table.Columns.Count; i++) { PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName); if (propertyInfo != null && dr[i] != DBNull.Value) propertyInfo.SetValue(model, dr[i], null); } return model; }