将LINQ查询返回给DataTable .NET 3.5? [英] Return LINQ query to DataTable .NET 3.5?

查看:256
本文介绍了将LINQ查询返回给DataTable .NET 3.5?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用LINQ查询两个 DataTables (通过解析Excel文件填充),并将它们加入到匹配的字段UPC中,如下所示:

I want to query two DataTables (populated by parsing Excel files) using LINQ and join them on a matching field, "UPC", as follows:

Dim query = From c In dt.AsEnumerable() _
Join r In dtUnits.AsEnumerable() _
On c.Field(Of String)("UPC") Equals r.Field(Of String)("UPC") _
Select New With {.UPC = r.Field(Of String)("UPC")}

此外,我想将此LINQ查询结果复制到DataTable。我发现一个方法 CopyToDataTable(),但它是在.NET 4.5,我们的服务器只支持.NET 3.5。

Additionally, I want to copy this LINQ query result to a DataTable. I found a method CopyToDataTable(), but it is in .NET 4.5, and our server only supports .NET 3.5.

如何在VB .NET 3.5中模拟此功能?

What can I do to emulate this functionality in VB .NET 3.5?

谢谢!

推荐答案

CopyToDataTable 自.NET 35以来已经存在。但问题是您要创建一个 DataTable 从头开始从匿名类型。那不行。

CopyToDataTable is already there since .NET 35. But the problem is that you want to create a DataTable "from the scratch" from an anonymous type. That doesn't work.

CopyToDataTable IEnumerable< DataRow> 只要。因此,您必须从加入的 DataTables 中选择一个 DataRow

CopyToDataTable is an extension for IEnumerable<DataRow> only. So you either have to select one DataRow from your joined DataTables:

Dim query = From c In dt.AsEnumerable() _
            Join r In dtUnits.AsEnumerable() _
            On c.Field(Of String)("UPC") Equals r.Field(Of String)("UPC") _
            Select c
Dim table = query.CopyToDataTable()

或使用这个使用反射的 ObjectShredder 不是最有效的方式( C#实现)。

or use this ObjectShredder which uses reflection, hence is not the most efficient way(C# implementation).

这篇关于将LINQ查询返回给DataTable .NET 3.5?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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