vb.net 将 LINQ 查询返回到 DataTable .NET 3.5?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13991729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return LINQ query to DataTable .NET 3.5?
提问by Yuriy Galanter
I want to query two DataTables(populated by parsing Excel files) using LINQ and join them on a matching field, "UPC", as follows:
我想DataTables使用 LINQ查询两个(通过解析 Excel 文件填充)并将它们连接到匹配字段“UPC”,如下所示:
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")}
Additionally, I want to copy this LINQ query result to a DataTable. I found a methodCopyToDataTable(), but it is in .NET 4.5, and our server only supports .NET 3.5.
此外,我想将此 LINQ 查询结果复制到 DataTable。我找到了一个方法CopyToDataTable(),但它在 .NET 4.5 中,而我们的服务器仅支持 .NET 3.5。
What can I do to emulate this functionality in VB .NET 3.5?
我该怎么做才能在 VB .NET 3.5 中模拟此功能?
Thank you!
谢谢!
回答by Tim Schmelter
CopyToDataTableis 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自 .NET 35 以来已经存在。但问题是您想DataTable从匿名类型“从头开始”创建一个。那行不通。
CopyToDataTableis an extension for IEnumerable<DataRow>only. So you either have to select oneDataRowfrom your joined DataTables:
CopyToDataTable只是一个扩展IEnumerable<DataRow>。所以你要么必须从你加入的中选择一个:DataRowDataTables
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()
or use this ObjectShredderwhich uses reflection, hence is not the most efficient way(C# implementation).
或使用此ObjectShredder它使用反射,因此不是最有效的方法(C#实现)。
回答by Yuriy Galanter
Take a look at this article:
看看这篇文章:
http://codecorner.galanter.net/2009/12/17/grouping-ado-net-datatable-using-linq/
http://codecorner.galanter.net/2009/12/17/grouping-ado-net-datatable-using-linq/
You can use .toDataTablemethod, but only if your LINQ Query returns actual DataTable rows. For a custom type you can use attached to the article code to perform the same.
您可以使用.toDataTable方法,但前提是您的 LINQ 查询返回实际的 DataTable 行。对于自定义类型,您可以使用附加到文章代码来执行相同的操作。
回答by user1622287
Pls read this article LINQ TO DATATABLE in WCF ,connecting to Adventure Database.
请阅读这篇文章 LINQ TO DATATABLE in WCF,connecting to Adventure Database。
Datasets doesnot implement IEnumerable/IQueryable interface,.
数据集没有实现 IEnumerable/IQueryable 接口。
So pls read this article.
所以请阅读这篇文章。
http://www.wnewsone.com/tutorials/wcf/ShowArticle.aspx?articleid=20143
http://www.wnewsone.com/tutorials/wcf/ShowArticle.aspx?articleid=20143

