集合通用列出匿名类型到System Data.IDataReader

时间:2016-10-24 09:23:11

标签: c# list datatable anonymous-types

我在这里有一个匿名列表,并尝试将其数据加载到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'

任何解决方案?

1 个答案:

答案 0 :(得分:1)

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?