public class User { public int ID { get; set; } public string Name { get; set; } } //对应数据库表: //User //字段:ID、Name
那么你也许需要编写将datatable 转换为实体对象的方法,便利datatable.rows 获得并填充。。
下面是我写的一个通用方法,分享+记录,便于日后直接Copy ~
private static List<T> TableToEntity<T>(DataTable dt) where T : class,new() { Type type = typeof(T); List<T> list = new List<T>(); foreach (DataRow row in dt.Rows) { PropertyInfo[] pArray = type.GetProperties(); T entity = new T(); foreach (PropertyInfo p in pArray) { if (row[p.Name] is Int64) { p.SetValue(entity, Convert.ToInt32(row[p.Name]), null); continue; } p.SetValue(entity, row[p.Name], null); } list.Add(entity); } return list; } // 调用: List<User> userList = TableToEntity<User>(YourDataTable);
更多C# DataTable 转换为 实体类对象实例相关文章请关注PHP中文网!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号