Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi all,

Really sorry to ask this as im sure its fairly simple once you know.

Im trying to join to datatables using linq and return columns from both tables and then insert the result into another datatable.

The problem is that I cant use the query.CopyToDataTable() method as there are anonymous types in the query (or something). Please see the code below.

I have been looking online now for absolutely ages! I have seen the ObjectShredder class advice given on MSDN but cant quite work it out, and i have tried a huge variety of other potential solutions, alas to no avail.

Could someone please either point out where im going wrong or may be a quick pointer on how to get the ObjectShredder Class to resolve this?

Any help at this stage is more than welcome!

Thanks in advance

Chris


The original bit of code:

SQL
Dim query = From a In dt _
    Join b In dtLossEvents _
    On _
    a.Field(Of Integer)("EventID") Equals b.Field(Of Integer)("EventID") _
    Select New With { _
                    a, _
                    b _
                    }







This it the latest flawed incarnation:

SQL
Dim query = From a In dt _
            Join b In dtLossEvents _
            On _
            a.Field(Of Integer)("EventID") Equals b.Field(Of Integer)("EventID") _
            Select New With { _
                             .Gross_Loss = a.Field(Of Double ("Gross_Loss"), _
                             .Net_Loss = a.Field(Of Double)("Net_Loss"), _
                             .EventID = b.Field(Of Integer)("EventID") _
}
Posted

1 solution

C++
Hi Chris;<br>
First add the the class and module to your project:
    Public Class ObjectShredder(Of T)
    Public Module CustomLINQtoDataSetMethods

They are located on the web page
    How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow
    <a href="http://msdn.microsoft.com/en-us/library/bb669096.aspx">http://msdn.microsoft.com/en-us/library/bb669096.aspx</a>

Have your two DataTables filled

Then modify your query to add the method AsEnumerable() to both tables as shown below

<pre>Dim query = From a In dt.AsEnumerable() _
            Join b In dtLossEvents.AsEnumerable() _
            On _
            a.Field(Of Integer)("EventID") Equals b.Field(Of Integer)("EventID") _
            Select New With { _
                .Gross_Loss = a.Field(Of Double ("Gross_Loss"), _
                .Net_Loss = a.Field(Of Double)("Net_Loss"), _
                .EventID = b.Field(Of Integer)("EventID") _
            }

Then execute the method CopyToDataTable on your query
Dim table As DataTable = query.CopyToDataTable()

Fernando


 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900