Fill Datatable from linq query
70,876
Since the query returns an IEnumerable of Type DataRow, you have to specify what to insert into the datatable, in this case DataRow.
DataTable dt = query.CopyToDataTable<DataRow>();
If you used
var query = //linq query of what you need for new datatable....
DataTable dt = query.CopyToDataTable();
Your table name is dt so select what you need from the original dt
var query = from c in db.something
where c.othersomething == "onlyyouknow"
orderby c.othersomething
select new { NewObject = c.othersomething };
DataTable MyDataTable = new DataTable();
myDataTable.Columns.Add(
new DataColumn()
{
DataType = System.Type.GetType("System.String"),//or other type
ColumnName = "Name" //or other column name
}
);
foreach (var element in query)
{
var row = MyDataTable.NewRow();
row["Name"] = element.NewObject;
myDataTable.Rows.Add(row);
}
Author by
Shantanu Sen
Updated on June 14, 2020Comments
-
Shantanu Sen almost 4 years
i am using the below code
IEnumerable<DataRow> query = from c in at.appointmentcalendars.AsEnumerable() select c; DataTable dt = query.CopyToDataTable();
But i am getting the below error
Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<appointmentcalendar>'
to'System.Collections.Generic.IEnumerable<System.Data.DataRow>'
. An explicit conversion exists (are you missing a cast?) -
dk14 over 7 yearsin order to share your knowledge you can create your own question + answer (it's completely fine on SO) and link it to this one