首页 > 其他 > 详细

DataTable与List<T>互转

时间:2018-03-05 19:27:16      阅读:198      评论:0      收藏:0      [点我收藏+]
平时写代码的时候经常会遇到DataTable与List<T>之间的转换操作,由于DataTable数据集合不像List<T>指定了对应的T类型,所以在操作的时候没有List<T>方便,为了方便两个集合的转换,特此写下以下类记录两者之间的互换。 class ModelConvertHelper<T> where T : new() { /// <summary> /// 把DataTable转换成指定类型的List /// </summary> /// <param name="dt"></param> /// <returns></returns> public static IList<T> ConvertDataTableToList(DataTable dt) { // 定义集合 IList<T> ts = new List<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; } /// <summary> /// 把泛型List转换成DataTable /// </summary> /// <param name="list"></param> /// <returns></returns> public static DataTable ConvertListToDataTable(List<T> list) { DataTable dt = new DataTable(); // 获得此模型的公共属性 PropertyInfo[] propertys = typeof(T).GetProperties(); foreach (PropertyInfo pi in propertys) { // 判断此属性是否有Getter if (!pi.CanRead) continue; dt.Columns.Add(pi.Name, pi.PropertyType); } foreach (T item in list) { propertys = item.GetType().GetProperties(); DataRow newRow = dt.NewRow(); foreach (PropertyInfo pi in propertys) { if (!pi.CanRead) continue; newRow[pi.Name] = pi.GetValue(item); } dt.Rows.Add(newRow); } return dt; } }

DataTable与List<T>互转

原文:http://blog.51cto.com/13492397/2083194

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!