集合泛型列表匿名类型到系统 Data.IDataReader
Collections Generic List anonymous type to System Data.IDataReader
我这里有一个匿名列表并试图将其数据加载到 Datatable 但出现错误
var empList1 = employees.Select(p => new { UserId = p.UserId, empName = p.FullName, EmpCode = p.EmployeeCode }).Distinct().ToList();
DataTable dtt = new DataTable();
// dtt.Load(empList1);
严重性代码说明项目文件行抑制状态工具
错误 CS1503 参数 1:无法从 'System.Collections.Generic.List<>' 转换为 'System.Data.IDataReader'
有什么解决办法吗??
DataTable.Load
method 需要一个 DataReader
但你给它一个 List<anonymoustype>
。您需要使用循环:
DataTable dtt = new DataTable();
dtt.Columns.Add("UserId", typeof(System.Guid));
dtt.Columns.Add("FullName", typeof(string));
dtt.Columns.Add("EmployeeCode ", typeof(string));
foreach(var employee in empList1)
dtt.Rows.Add(employee.UserId, employee.FullName, employee.EmployeeCode);
这是高效且可读的,但如果你需要一个通用的单行代码,你必须使用反射:Convert generic List/Enumerable to DataTable?
我这里有一个匿名列表并试图将其数据加载到 Datatable 但出现错误
var empList1 = employees.Select(p => new { UserId = p.UserId, empName = p.FullName, EmpCode = p.EmployeeCode }).Distinct().ToList();
DataTable dtt = new DataTable();
// dtt.Load(empList1);
严重性代码说明项目文件行抑制状态工具 错误 CS1503 参数 1:无法从 'System.Collections.Generic.List<>' 转换为 'System.Data.IDataReader'
有什么解决办法吗??
DataTable.Load
method 需要一个 DataReader
但你给它一个 List<anonymoustype>
。您需要使用循环:
DataTable dtt = new DataTable();
dtt.Columns.Add("UserId", typeof(System.Guid));
dtt.Columns.Add("FullName", typeof(string));
dtt.Columns.Add("EmployeeCode ", typeof(string));
foreach(var employee in empList1)
dtt.Rows.Add(employee.UserId, employee.FullName, employee.EmployeeCode);
这是高效且可读的,但如果你需要一个通用的单行代码,你必须使用反射:Convert generic List/Enumerable to DataTable?