标签:调用 技术 字段 wro info 方法 tac bnu gety
闲来无事,只有写代码啦,以下为DataTable转List与List转DataTable的两个方法,主要技术点用到了反射原理:
/// <summary> /// 模型转换类 /// </summary> public class ConvertModel { /// <summary> /// DataTable转List /// </summary> /// <typeparam name="T">list中的类型</typeparam> /// <param name="dt">要转换的DataTable</param> /// <returns></returns> public static List<T> DatatTableToList<T>(DataTable dt) where T : class, new() { List<T> list = new List<T>(); T t = new T(); PropertyInfo[] prop = t.GetType().GetProperties(); //遍历所有DataTable的行 foreach (DataRow dr in dt.Rows) { t = new T(); //通过反射获取T类型的所有成员 foreach (PropertyInfo pi in prop) { //DataTable列名=属性名 if (dt.Columns.Contains(pi.Name)) { //属性值不为空 if (dr[pi.Name] != DBNull.Value) { object value = Convert.ChangeType(dr[pi.Name], pi.PropertyType); //给T类型字段赋值 pi.SetValue(t, value, null); } } } //将T类型添加到集合list list.Add(t); } return list; } /// <summary> /// List转换为DataTable /// </summary> /// <typeparam name="T">List中的类型</typeparam> /// <param name="list">要转换的list</param> /// <returns></returns> public static DataTable ListToDataTable<T>(List<T> list) where T : class { DataTable dt = new DataTable(); PropertyInfo[] prop = typeof(T).GetProperties(); DataColumn[] ColumnArr = prop.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray(); dt.Columns.AddRange(ColumnArr); foreach (T t in list) { DataRow dr = dt.NewRow(); foreach (PropertyInfo pi in prop) { if (dt.Columns.Contains(pi.Name)) { if (pi.GetValue(t) != null) { dr[pi.Name] = pi.GetValue(t); } } } dt.Rows.Add(dr); } return dt; } }
调用:
DataTable dt = new DataTable(); dt.Columns.Add("Id"); dt.Columns.Add("Sex"); dt.Columns.Add("Age"); dt.Columns.Add("Height"); DataRow dr = dt.NewRow(); dr["Id"] = 1; dr["Sex"] = 1; dr["Age"] = 18; dr["Height"] = 190; dt.Rows.Add(dr); //将DataTable转换为List<Persion> List<Persion> list1 = ConvertModel.DatatTableToList<Persion>(dt); List<Persion> list = new List<Persion>() { new Persion(){Id=1,Sex=1,Age=26,Height=168}, new Persion(){Id=2,Sex=0,Age=26,Height=168}, }; //将List<Persion>转换为DataTable DataTable dt1 = ConvertModel.ListToDataTable<Persion>(list);
C#之DataTable转List与List转Datatable
标签:调用 技术 字段 wro info 方法 tac bnu gety
原文地址:http://www.cnblogs.com/luckyyang/p/7390369.html