问题
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")}
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.
What can I do to emulate this functionality in VB .NET 3.5?
Thank you!
回答1:
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
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()
or use this ObjectShredder which uses reflection, hence is not the most efficient way(C# implementation).
回答2:
Take a look at this article:
http://codecorner.galanter.net/2009/12/17/grouping-ado-net-datatable-using-linq/
You can use .toDataTable
method, 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.
回答3:
Pls read this article LINQ TO DATATABLE in WCF ,connecting to Adventure Database.
Datasets doesnot implement IEnumerable/IQueryable interface,.
So pls read this article.
http://www.wnewsone.com/tutorials/wcf/ShowArticle.aspx?articleid=20143
来源:https://stackoverflow.com/questions/13991729/return-linq-query-to-datatable-net-3-5