Hi
How to store the results of Linq Query in Datatable
C#
List Result = (from t in context.View_SessionBookPlanningRecommendations
orderby t.StudentID
where StudentCollection.Contains(t.StudentID.ToString())
select t).ToList();Thanks

Naimish MakwanaRank #324 · 7.7K reputationPosted Apr 26, 2023, 1:24 AM EDT
To store the results of a LINQ query in a DataTable, you can use the CopyToDataTable() method. Here's how you can modify your code to do so:
List Result = (from t in context.View_SessionBookPlanningRecommendations orderby t.StudentID where StudentCollection.Contains(t.StudentID.ToString()) select t).ToList(); DataTable dt = new DataTable(); if (Result.Any()) { dt = Result.CopyToDataTable(); }The
CopyToDataTable()method creates a new DataTable based on the results of the LINQ query. If the query returns no results, an empty DataTable is created. You can then use thedtDataTable to perform further operations, such as displaying the results in a data grid or exporting them to a file.Thanks
Amit MohantyRank #112 · 20K reputationPosted Apr 26, 2023, 12:24 AM EDT
DataTable dt = new DataTable(); DataRow[] rows = (from t in context.View_SessionBookPlanningRecommendations orderby t.StudentID where StudentCollection.Contains(t.StudentID.ToString()) select dt.LoadDataRow(new object[] { t.Column1, // replace with the actual column names of your table t.Column2, t.Column3, // ... }, false)).ToArray(); dt.Rows.AddRange(rows);