C#使用泛型方法将Datatable转换成List对象集合
在项目中遇到需要将Datatable转换成对象的需求,通过dr[0]取下标这种获取,如果数据的顺序发生了改变则需要改变全部,工作量大
foreach (DataRow dr in dt.Rows) { CheckDetail info = new CheckDetail(); info.org_id = dr[0].ToString(); info.am_line_id = dr[1].ToString(); info.component = dr[2].ToString(); info.standard = dr[3].ToString(); info.frequency = dr[4].ToString(); info.status_code = dr[5].ToString(); info.status_name = dr[6].ToString(); info.activity_type = dr[7].ToString(); info.activity_type_name = dr[8].ToString(); info.check_results = dr[9].ToString(); info.remark = dr[10].ToString(); info.creation_date = FrameWork.ToDateTimeWithNull(dr[11].ToString()); info.created_by = dr[12].ToString(); info.last_updated_date = FrameWork.ToDateTimeWithNull(dr[13].ToString()); info.last_updated_by = dr[14].ToString(); info.am_head_id = dr[15].ToString(); info.check = dr[16].ToString(); info.Seq = Seq; list.Add(info); Seq++; }
如果采用dr["columnName"]取列名的方式,一旦数据字段多了,工作量同样不小
foreach (DataRow dr in dt.Rows) { DeviceInfo info = new DeviceInfo(); info.Line_ID = dr["LINE_ID"].ToString(); info.Resource_ID = dr["RESOURCE_ID"].ToString(); info.Item_ID = dr["ITEM_ID"].ToString(); info.Item_Desc = dr["ITEM_DESC"].ToString(); info.Uom = dr["UOM"].ToString(); info.Desc = dr["DESCRIPTIONS"].ToString(); info.Avail_Qty = dr["AVAIL_QTY"].ToString(); info.Lot_Qty = dr["LOT_QTY"].ToString(); info.Flag = Convert.ToInt32(dr["FLAG"].ToString()); info.Plan_Flag = Convert.ToInt32(dr["PLAN_FLAG"].ToString()); info.Item_Code = dr["ITEM_CODE"].ToString(); info.Flag_Result = info.Flag == 1 ? true : false; info.Plan_Flag_Result = info.Plan_Flag == 1 ? true : false; list.Add(info); }
所以才有了通过泛型+反射的这种方式 这种方式有个致命的缺点:对象属性的大小写一定要与DataTable中列名一致,不然无法获取到数据
/// <summary> /// 将Datatable数据转换成实体对象集合 /// </summary> /// <typeparam name="T">对象</typeparam> /// <param name="dt">Datatable数据</param> /// <returns></returns> public List<T> ConvertDataTableToList<T>(DataTable dt) where T : new() { List<T> list = new List<T>(); foreach (DataRow row in dt.Rows) { T obj = new T(); foreach (DataColumn column in dt.Columns) { string columnName = column.ColumnName; PropertyInfo property = typeof(T).GetProperty(columnName, BindingFlags.Public | BindingFlags.Instance); if (property != null && row[columnName] != DBNull.Value) { if (property.PropertyType == typeof(DateTime?)) { DateTime? value = null; string dateString = row[columnName].ToString(); DateTime parsedDate; if (DateTime.TryParse(dateString, out parsedDate)) { value = parsedDate; } property.SetValue(obj, value); } else if (property.PropertyType == typeof(int?)) { int? value = null; string dateString = row[columnName].ToString(); int parsedDate; if (int.TryParse(dateString, out parsedDate)) { value = parsedDate; } property.SetValue(obj, value); } else if (property.PropertyType == typeof(bool?)) { bool? value = null; string dateString = row[columnName].ToString(); bool parsedDate; if (bool.TryParse(dateString, out parsedDate)) { value = parsedDate; } property.SetValue(obj, value); } else { object value = Convert.ChangeType(row[columnName], property.PropertyType); property.SetValue(obj, value); } } } list.Add(obj); } return list; }
下面是改良版本,这个版本可以直接用,不用担心对象属性大小写与DataTable列名不一致问题
public static List<T> ConvertDataTableToList<T>(DataTable dataTable) where T : new() { List<T> result = new List<T>(); if (dataTable == null || dataTable.Rows.Count == 0) { return result; } foreach (DataRow row in dataTable.Rows) { T item = CreateItemFromRow<T>(row); result.Add(item); } return result; } private static T CreateItemFromRow<T>(DataRow row) where T : new() { T item = new T(); PropertyInfo[] properties = typeof(T).GetProperties(); foreach (PropertyInfo property in properties) { string columnName = property.Name; if (!row.Table.Columns.Contains(columnName)) { foreach (DataColumn column in row.Table.Columns) { if (string.Equals(column.ColumnName, columnName, StringComparison.OrdinalIgnoreCase)) { columnName = column.ColumnName; break; } } } if (row.Table.Columns.Contains(columnName)) { if (property.PropertyType == typeof(DateTime?)) { DateTime? value = null; string dateString = row[columnName].ToString(); DateTime parsedDate; if (DateTime.TryParse(dateString, out parsedDate)) { value = parsedDate; } property.SetValue(item, value); } else if (property.PropertyType == typeof(int?)) { int? value = null; string dateString = row[columnName].ToString(); int parsedDate; if (int.TryParse(dateString, out parsedDate)) { value = parsedDate; } property.SetValue(item, value); } else if (property.PropertyType == typeof(bool?)) { bool? value = null; string dateString = row[columnName].ToString(); bool parsedDate; if (bool.TryParse(dateString, out parsedDate)) { value = parsedDate; } property.SetValue(item, value); } else { object value = Convert.ChangeType(row[columnName], property.PropertyType); property.SetValue(item, value); } } } return item; }