Shaikh Aamir Shaikh Aamir - 1 month ago 12
C# Question

Collections Generic List anonymous type to System Data.IDataReader

i have a anonymous list here and trying to load its data to Datatable but getting an error

var empList1 = employees.Select(p => new { UserId = p.UserId, empName = p.FullName, EmpCode = p.EmployeeCode }).Distinct().ToList();

DataTable dtt = new DataTable();
// dtt.Load(empList1);


Severity Code Description Project File Line Suppression State Tool
Error CS1503 Argument 1: cannot convert from 'System.Collections.Generic.List<>' to 'System.Data.IDataReader'


any solution ??

Answer

The DataTable.Load method expects a DataReader but you're giving it a List<anonymoustype>. You need to use a loop:

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);

This is efficient and readable, but if you need a generic one-liner you have to use reflection: Convert generic List/Enumerable to DataTable?

Comments