C# DataTable 转换为 实体类对象实例_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

C# DataTable 转换为 实体类对象实例

发布时间:2026-01-17  |  点击率:

复制代码 代码如下:
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);

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598