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
571 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


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

...