DataTable转换成List<T>
很多时候需要将DataTable转换成一组model,直接对model执行操作会更加方便直观。
代码如下:
1 public static class DataTableToModel 2 { 3 public static List<T> ConvertToModel<T>(this DataTable dt) 4 { 5 if (dt == null || dt.Rows.Count == 0) 6 { 7 return null; 8 } 9 10 var result = new List<T>(); 11 12 var objType = typeof(T); 13 var properties = objType.GetProperties(); 14 var columnNames = GetDataTableColumnNames(dt); 15 16 foreach (DataRow dr in dt.Rows) 17 { 18 var obj = objType.Assembly.CreateInstance(objType.FullName); 19 //var obj = Activator.CreateInstance(objType); 20 foreach (var property in properties) 21 { 22 if (columnNames.Contains(property.Name)) 23 { 24 var cellValue=dr[property.Name]; 25 object propertyValue=cellValue; 26 27 //非泛型 28 if (!property.PropertyType.IsGenericType) 29 { 30 propertyValue = cellValue == null ? null : Convert.ChangeType(cellValue, property.PropertyType); 31 } 32 else //泛型Nullable<> 33 { 34 Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition(); 35 if (genericTypeDefinition == typeof(Nullable<>)) 36 { 37 propertyValue = cellValue == null ? null : Convert.ChangeType(cellValue, Nullable.GetUnderlyingType(property.PropertyType)); 38 } 39 } 40 41 property.SetValue(obj, propertyValue, null); 42 } 43 } 44 45 result.Add((T)obj); 46 } 47 48 return result; 49 } 50 51 private static HashSet<string> GetDataTableColumnNames(DataTable dt) 52 { 53 var columnNames = new HashSet<string>(); 54 foreach (DataColumn column in dt.Columns) 55 { 56 columnNames.Add(column.ColumnName); 57 } 58 return columnNames; 59 } 60 }