/// <summary> /// 转换工具类 /// </summary> /// <typeparam name="T"></typeparam> public class ConvertHelper<T> where T : new() { /// <summary> /// DataTable转换为IList /// </summary> /// <param name="dt"></param> /// <returns></returns> public static IList<T> ConvertToIList(DataTable dt) { // 定义集合 IList<T> list = new List<T>(); // 获得此模型的类型 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); } } list.Add(t); } return list; } /// <summary> /// Ilist 转换成 DataSet /// </summary> /// <param name="list"></param> /// <returns></returns> public static DataSet ConvertToDataSet<T>(IList<T> list) { DataSet ds = new DataSet(); ds.Tables.Add(ConvertToDataTable<T>(list)); return ds; } /// <summary> /// Ilist 转换成 DataTable /// </summary> /// <param name="list"></param> /// <returns></returns> public static DataTable ConvertToDataTable<T>(IList<T> list) { if (list == null || list.Count <= 0) { return null; } DataTable dt = new DataTable(typeof(T).Name); DataColumn column; DataRow row; PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (T t in list) { if (t == null) { continue; } row = dt.NewRow(); for (int i = 0, j = myPropertyInfo.Length; i < j; i++) { PropertyInfo pi = myPropertyInfo[i]; string name = pi.Name; if (dt.Columns[name] == null) { column = new DataColumn(name, pi.PropertyType); dt.Columns.Add(column); } row[name] = pi.GetValue(t, null); } dt.Rows.Add(row); } return dt; } }