user997501 user997501 - 3 months ago 31
C# Question

Fill Datatable from linq query

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

Answer

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