C#中泛型举例List与DataTable相互转换

一、 DataTable转换到List

////// TableToList///public class TableListConverter where T : class, new(){public static IList TableToList(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; if (dt.Columns.Contains(tempName))// 检查DataTable是否包含此列{if (!pi.CanWrite) continue; // 判断此属性是否有Setterobject value = https://www.it610.com/article/dr[tempName]; if (value != DBNull.Value)pi.SetValue(t, value, null); }}ts.Add(t); }return ts; }}

【C#中泛型举例List与DataTable相互转换】应用:
// 获得查询结果 DataTable dt = DbHelper.ExecuteDataTable("..."); // 把DataTable转换为IList IList users = TableListConverter.TableToList(dt);

二、 List转换到DataTable
////// ListToTable///public class TableListConverter{public static DataTable ListToTable(IList list) where T : class, new(){if (list == null) return null; Type type = typeof(T); DataTable dt = new DataTable(); PropertyInfo[] properties = Array.FindAll(type.GetProperties(), p => p.CanRead); //判断此属性是否有GetterArray.ForEach(properties, prop => { dt.Columns.Add(prop.Name, prop.PropertyType); }); //添加到列foreach (T t in list){DataRow row = dt.NewRow(); Array.ForEach(properties, prop =>{row[prop.Name] = prop.GetValue(t, null); }); //添加到行dt.Rows.Add(row); }return dt; }}

应用:
//IList users DataTable dt =TableListConverter.ListToTable(users)

C#中泛型举例List与DataTable相互转换
文章图片

C#中泛型举例List与DataTable相互转换
文章图片

到此这篇关于C#中泛型举例List与DataTable相互转换的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读