Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...