0

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
    It is available in .NET 3.5 also. http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.copytodatatable(v=vs.90).aspx – Hamlet Hakobyan Dec 21 '12 at 14:18
  • That's strange, it's not appearing in Intellisense, and I believe I have the correct references and imports--`Imports System.Linq` and `Imports System.Data`--am I missing something? –  Dec 21 '12 at 14:23
  • 1
    @user1496816: It's not available in Intellisense because it's an extension for `IEnumerabley` and you're selecting an `IEnumerable`. – Tim Schmelter Dec 21 '12 at 14:33

3 Answers3

3

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).

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Excellent. Thank you. Because I am not too concerned with performance, I think I'm going to use the `ObjectShredder`method. This is a little above my head, though. I added both `DataSetLinqOperators.vb` and `ObjectShredder.vb` to my project, but I don't know how to implement them. –  Dec 21 '12 at 14:49
  • 1
    You need to add the extension methods: http://msdn.microsoft.com/en-us/library/bb669096.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2 – Tim Schmelter Dec 21 '12 at 14:55
1

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.

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
-1

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