Best Practice: Convert LINQ Query result to a DataTable without looping
Use Linq to Dataset. From the MSDN : Creating a DataTable From a Query (LINQ to DataSet)
// Query the SalesOrderHeader table for orders placed
// after August 8, 2001.
IEnumerable<DataRow> query =
from order in orders.AsEnumerable()
where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
select order;
// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();
If you have anonymous types :
From the Coder Blog : Using Linq anonymous types and CopyDataTable
It explains how to use MSDN's How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow
Looping Through LINQ Queries and Appending Results to DataTable
You just need do results.Merge(toMerge);
you shouldn't do results = results.Merge(toMerge);
. Because Merg
function acts on caller DataTable, and doesn't return anything.
LINQ query copytodatatable
First create a table with the schema, then Select with the result of IEnumerable<DataRow>
in order to use CopyToDataTable()
var temp = new DataTable();
temp.Columns.Add("Name", typeof(string));
temp.Columns.Add("Quantity", typeof(int));
var query = dt.AsEnumerable()
.GroupBy(row => row.Field<string>("Name"))
.Select(g =>
{
var row = temp.NewRow();
row.SetField("Name", g.Key);
row.SetField("Quantity", g.Count());
return row;
}).CopyToDataTable();
Related Topics
Why C# Won't Allow Field Initializer with Non-Static Fields
Interaction Between Webbrowser Control and Windows Forms
What Happens While Waiting on a Task's Result
How Do Events Cause Memory Leaks in C# and How Do Weak References Help Mitigate That
C#: Detecting Which Application Has Focus
How to Add the Same Column to All Entities in Ef Core
Is .Getawaiter().Getresult(); Safe for General Use
Data Binding Directly to a Store Query (Dbset, Dbquery, Dbsqlquery) Is Not Supported
Which Checkedlistbox Event Triggers After a Item Is Checked
With Rx, How to Ignore All-Except-The-Latest Value When My Subscribe Method Is Running
Datagridview with Button Control - Delete Row
Conditional Datagridview Formatting