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

public class User 
{ 
        public int ID { get; set; } 
        public string Name { get; set; } 
} 

//对应数据库表: 
//User 
//字段:ID、Name     
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);

以便以后使用!copy过来

原文地址:https://www.cnblogs.com/congge/p/7277914.html