Best Practice: Convert Linq Query Result to a Datatable Without Looping

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



Leave a reply



Submit