最佳实践:将LINQ查询结果的DataTable不用循环 [英] Best Practice: Convert LINQ Query result to a DataTable without looping

查看:123
本文介绍了最佳实践:将LINQ查询结果的DataTable不用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是LINQ查询结果转换为一个新的DataTable的最佳做法?结果
我能找到一个更好的解决办法比的foreach每个结果项目?

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?

修改
 AnonymousType

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
             };

编辑2:
我得到异常的本地顺序不能在LINQ用于除载有()运算符SQL执行查询操作的。的,因为我尝试执行查询
并找到了解决办法在这里<一个href=\"http://stackoverflow.com/questions/331345/ienumerable-except-wont-work-so-what-do-i-do\">IEnumerable.Except不会工作,那么我该怎么办?结果和<一个href=\"http://social.msdn.microsoft.com/Forums/en/linqprojectgeneral/thread/403d2e05-af6b-4300-ba7b-79588e6b779c\">Need LINQ帮助

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

推荐答案

使用LINQ到数据集。从MSDN:创建一个DataTable从查询(LINQ到DataSet的

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>();

如果您有匿名类型:

从codeR博客:<一href=\"http://www.the$c$crblog.com/2008/10/14/using-linq-anonymous-types-and-copytodatatable-to-avoid-excess-database-calls/\">Using LINQ的匿名类型和CopyDataTable

这说明了如何使用MSDN的如何:实现CopyToDataTable凡泛型类型T不是一个DataRow

It explains how to use MSDN's How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow

这篇关于最佳实践:将LINQ查询结果的DataTable不用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆