1

I have two dataTables which I want to union to make one final dataTable. Both are results of different functions.

I tried this :

dtfinal = dt1.Copy()
dtfinal = dt2.Copy()

But here dt2 data is replaced by dt1. What should be used to get union of both into the final dt.

Muriel Mi
  • 21
  • 5
  • Can I just double check what you mean by "union"? Are you asking in the SQL UNION sense? The UNION ALL sense? Or is "union" a typo and you mean a join? – Caius Jard Jan 21 '22 at 06:30

1 Answers1

1

You can use DataTable.Merge:

Dim allTables() As DataTable = {dt1, dt2}
Dim dtfinal = new DataTable("dtfinal")
dtfinal.BeginLoadData() ' Turns off notifications, index maintenance, and constraints while loading data
For Each t As DataTable in allTables
    dtfinal.Merge(t) ' same as table.Merge(t, false, MissingSchemaAction.Add)
Next
dtfinal.EndLoadData()

If you don't have primary keys specified you could end up with repeating rows where you actually want to merge them. Then either specify the PKs or use this method i have provided here(needs conversion from C#):

Combining n DataTables into a Single DataTable

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939