using System; using System.Collections.Generic; using System.Data; namespace ModelToDataTableDemo { /// <summary> /// https://www.cnblogs.com/LifeDecidesHappiness/p/15592278.html /// C# DataTable 转换 Model实体类,DataTable 转换 List 集合 /// LDH @ 2021-11-23 /// </summary> internal class Program { private static void Main() { Console.Title = "C# DataTable 转换 Model实体类,DataTable 转换 List 集合"; ModelToDataTable(); Console.ReadKey(); } private static void ModelToDataTable() { // 创建一个新的DataTable var dt = new DataTable("User"); dt.Columns.Add("UserName", typeof(string)); dt.Columns.Add("Password", typeof(string)); dt.Columns.Add("Age", typeof(int)); for (var i = 0; i < 5; ++i) { var dr = dt.NewRow(); dr["UserName"] = "用户名" + i; dr["Password"] = "密码" + i; dr["Age"] = 20; dt.Rows.Add(dr); // DataTable 转换为实体 var user = DataTableToModel<User>(dt); Console.WriteLine("UserName:" + user.UserName); } // DataTable 转换为List var users = DataTableToList<User>(dt); Console.WriteLine("User Count:" + users.Count); } /// <summary> /// DataTable -> Model /// </summary> /// <typeparam name="T">数据项</typeparam> /// <param name="dt">DataTable</param> /// <returns></returns> public static T DataTableToModel<T>(DataTable dt) where T : new() { if (dt == null || dt.Rows.Count == 0) return default; var t = new T(); // 获取行数据 var dr = dt.Rows[0]; // 获取栏目 var columns = dt.Columns; // 获得此模型的公共属性 var property = t.GetType().GetProperties(); foreach (var pi in property) { var name = pi.Name; // 检查DataTable是否包含此列 if (columns.Contains(name)) { if (!pi.CanWrite) continue; var value = dr[name]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } return t; } /// <summary> /// DataTable -> List /// </summary> /// <typeparam name="T">数据项</typeparam> /// <param name="dt">DataTable</param> /// <returns></returns> public static List<T> DataTableToList<T>(DataTable dt) where T : new() { if (dt == null || dt.Rows.Count == 0) return new List<T>(); // 定义集合 var list = new List<T>(); // 获取栏目 var columns = dt.Columns; foreach (DataRow dr in dt.Rows) { var t = new T(); // 获得此模型的公共属性 var property = t.GetType().GetProperties(); foreach (var pi in property) { var name = pi.Name; // 检查DataTable是否包含此列 if (columns.Contains(name)) { if (!pi.CanWrite) continue; var value = dr[name]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } list.Add(t); } return list; } } }
namespace ModelToDataTableDemo { /// <summary> /// 用户 /// </summary> public class User { /// <summary> /// 用户名 /// </summary> public string UserName { get; set; } /// <summary> /// 密码 /// </summary> public string Password { get; set; } /// <summary> /// 年龄 /// </summary> public int Age { get; set; } } }