Chrisetiquette
Chrisetiquette

Reputation: 321

Merge two DataTables using an Inner Join in vb.net

I have two DataTables that need to be merged together. Both Tables have a field in it called "Code" Basically if one table has a certain code, it merges with the corresponding code in the other table, getting that rows values merged into it. I would say its like merging two tables together in SQL using an inner join.

Needs to be in vb.net please!

Upvotes: 0

Views: 2125

Answers (1)

Joseph Rosson
Joseph Rosson

Reputation: 354

Here is a VB conversion of this answer.

Dim dt1 As New DataTable()
dt1.Columns.Add("CustID", GetType(Integer))
dt1.Columns.Add("ColX", GetType(Integer))
dt1.Columns.Add("ColY", GetType(Integer))

Dim dt2 As New DataTable()
dt2.Columns.Add("CustID", GetType(Integer))
dt2.Columns.Add("ColZ", GetType(Integer))

For i As Integer = 1 To 5
    Dim row As DataRow = dt1.NewRow()
    row("CustID") = i
    row("ColX") = 10 + i
    row("ColY") = 20 + i
    dt1.Rows.Add(row)

    row = dt2.NewRow()
    row("CustID") = i
    row("ColZ") = 30 + i
    dt2.Rows.Add(row)
Next

Dim results = From table1 In dt1.AsEnumerable()Join table2 In      dt2.AsEnumerable() On CInt(table1("CustID")) = CInt(table2("CustID"))New With { _
    Key .CustID = CInt(table1("CustID")), _
    Key .ColX = CInt(table1("ColX")), _
    Key .ColY = CInt(table1("ColY")), _
    Key .ColZ = CInt(table2("ColZ")) _
}
For Each item As var In results
    Console.WriteLine([String].Format("ID = {0}, ColX = {1}, ColY = {2}, ColZ = {3}", item.CustID, item.ColX, item.ColY, item.ColZ))
Next
Console.ReadLine()

Upvotes: 3

Related Questions