user997501 user997501 - 1 month ago 5
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
. An
explicit conversion exists (are you missing a cast?)


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