using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace HT.Cloud.Code { public static class DataTableExtends { public static List> DataTabletoList(this DataTable dt) { List> list = new List>(); foreach (DataRow dr in dt.Rows)//每一行信息,新建一个Dictionary,将该行的每列信息加入到字典 { Dictionary result = new Dictionary(); foreach (DataColumn dc in dt.Columns) { result.Add(dc.ColumnName, dr[dc].ToString()); } list.Add(result); } return list; } } public class DataTableConvertModel where T : new() { public static List ConvertDataTableToList(DataTable dt) { // 定义集合 List ts = new List(); // 获得此模型的类型 Type type = typeof(T); string tempName = ""; foreach (DataRow dr in dt.Rows) { T t = new T(); // 获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name; // 检查DataTable是否包含此列 if (dt.Columns.Contains(tempName)) { // 判断此属性是否有Setter if (!pi.CanWrite) continue; object value = dr[tempName]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } ts.Add(t); } return ts; } public static IList ConvertDataTableToIList(DataTable dt) { // 定义集合 IList ts = new List(); // 获得此模型的类型 Type type = typeof(T); string tempName = ""; foreach (DataRow dr in dt.Rows) { T t = new T(); // 获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name; // 检查DataTable是否包含此列 if (dt.Columns.Contains(tempName)) { // 判断此属性是否有Setter if (!pi.CanWrite) continue; object value = dr[tempName]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } ts.Add(t); } return ts; } public static T ConvertDataTableToModel(DataTable dt) { if (dt == null) return default(T); // 定义集合 // 获得此模型的类型 Type type = typeof(T); string tempName = ""; T t = new T(); if (dt.Rows.Count > 0) { var dr = dt.Rows[0]; // 获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name; // 检查DataTable是否包含此列 if (dt.Columns.Contains(tempName)) { // 判断此属性是否有Setter if (!pi.CanWrite) continue; object value = dr[tempName]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } return t; } else return default(T); } } }