IEnumerable to datatable

91 views Asked by At

Please tell me how to write the result of a query in a DataTable?

var result = from clients in Clients_dt.AsEnumerable()
             join cities in Cities_dt.AsEnumerable()
                  on clients.Field<int> ("CityId") equals cities.Field<int> ("ID") into ClientCityGroup
             from subCities in ClientCityGroup.DefaultIfEmpty()
             select new 
                    {
                        Name = clients.Field <string> ("Name"),
                        City = subCities.Field <string> ("Name")
                    };

I tried using CopyToDatatable().

1

There are 1 answers

3
jdweng On

CopyToDataTable only works if the input is a DataTable. You have to create the DataTable before you can add data to the table.

Public DataTable GetTable(var results)
{
   DataTable dt = new DataTable();
   dt.Columns.Add("Name", typeof(string));
   dt.Columns.Add("City", typeof(string));

   foreach(var row in result)
   {
     dt.Rows.Add(new object[] { row.Name, row.City });
   }
   return dt;
}