Return LINQ query to DataTable .NET 3.5?

孤街浪徒 提交于 2019-12-25 06:49:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!