Rami Shareef Rami Shareef - 2 years ago 103
C# Question

Best Practice: Convert LINQ Query result to a DataTable without looping

What is the best practice to convert LINQ-Query result to a new DataTable?

can i find a solution better than foreach every result item?

EDIT
AnonymousType

var rslt =
from eisd in empsQuery
join eng in getAllEmployees()
on eisd.EMPLOYID.Trim() equals eng.EMPLOYID.Trim()
select new
{
eisd.CompanyID,
eisd.DIRECTID,
eisd.EMPLOYID,
eisd.INACTIVE,
eisd.LEVEL,
eng.EnglishName
};


EDIT 2:
I got exception 'Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.' as i try to execute the query
and found the solution here IEnumerable.Except wont work, so what do I do?
and Need linq help

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download