C#DataTable转List和List转DataTable

网友投稿 486 2022-11-10

C#DataTable转List和List转DataTable

C#DataTable转List和List转DataTable

DataTable 转换为List 集合

///

/// DataTable 转换为List 集合 /// /// 类型 /// DataTable /// public static List ToList(this DataTable dt) where T : class,new() { //创建一个属性的列表 List prlist = new List(); //获取TResult的类型实例 反射的入口 Type t = typeof(T); //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 Array.ForEach(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); }); //创建返回的集合 List oblist = new List(); foreach (DataRow row in dt.Rows) { //创建TResult的实例 T ob = new T(); //找到对应的数据 并赋值 //prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); }); prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) { p.SetValue(ob, row[p.Name], null); } else { if (p.PropertyType == typeof(string)) { p.SetValue(ob, string.Empty, null); } } }); //放入到返回的集合中. oblist.Add(ob); } return oblist; }

List转DataTable

public static class ListExtension { public static DataTable ListConvertDataTable(List model, string TableName) where T : class { try { Type value = typeof(T); List list = new List(value.GetProperties()); //属性列表 DataTable table = new DataTable();//实例化datatable table.TableName = TableName; //表名 foreach (var property in list) { //获取属性数据类型 Type PropertyType = property.PropertyType; //验证数据类型是否为空 if (PropertyType.IsGenericType && PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { PropertyType = property.PropertyType.GetGenericArguments()[0]; } table.Columns.Add(property.Name, PropertyType); } foreach (var dataValue in model) { DataRow row = table.NewRow(); list.ForEach(p => { row[p.Name] = p.GetValue(dataValue); }); table.Rows.Add(row); } return table; } catch (Exception ex) { return null; } } }

讲DataRow转成Model

///

/// DataRow 转换成 Model /// /// /// /// public static T ConvertToModel(this System.Data.DataRow dr) where T : new() { T model = new T(); foreach (PropertyInfo pInfo in model.GetType().GetProperties()) { object val = getValueByColumnName(dr, pInfo.Name); pInfo.SetValue(model, val, null); } return model; } /// /// 获取该列的值 /// /// /// /// public static object getValueByColumnName(System.Data.DataRow dr, string columnName) { if (dr.Table.Columns.IndexOf(columnName) >= 0) { if (dr[columnName] == DBNull.Value) { return null; } return dr[columnName]; } return null; }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Ext.js项目(二)
下一篇:ERP产品购进批量提交文件(三十六)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~