📜  如何将数据表映射到c#代码示例中的列表

📅  最后修改于: 2022-03-11 14:49:22.452000             🧑  作者: Mango

代码示例1
public List ConvertToList(DataTable dt)
{
    var columnNames = dt.Columns.Cast()
            .Select(c => c.ColumnName)
            .ToList();
    var properties = typeof(T).GetProperties();
    return dt.AsEnumerable().Select(row =>
    {
        var objT = Activator.CreateInstance();
        foreach (var pro in properties)
        {
            if (columnNames.Contains(pro.Name))
            {
                 PropertyInfo pI = objT.GetType().GetProperty(pro.Name);
                 pro.SetValue(objT, row[pro.Name] == DBNull.Value ? null : Convert.ChangeType(row[pro.Name], pI.PropertyType));
            }
        }
        return objT;
   }).ToList();
}