简体   繁体   中英

Copy columns from one datatable to another datatable

I've following requirement. I've two data tables structured as follows:

dt1:
columns: PrimaryKey, Style, Color, OTS0, OTS1
data: 1 S1 C1 5 6
2 S1 C2 1 2

dt2:
columns: PrimaryKey, Style, Color, OTS2, OTS3
data: 1 S1 C1 1 2
2 S1 C2 3 4

I need to merge above two data tables and the final result data table should be structured as below: dtResult:
columns: PrimaryKey, Style, Color, OTS0, OTS1, OTS2, OTS3
data: 1 S1 C1 5 6 1 2
2 S1 C2 1 2 3 4

how can we achieve this? (is there any direct way with out using Linq?) Please help!!

Assuming the data tables have the same number of rows, this might work:

VB.NET:

Dim i As Integer = 0
Dim i2 As Integer
Dim Colinx As Integer
Do Until i = dt1.Columns.Count
If dt1.Columns(i).ColumnName.Contains("OTS") Then
Colinx = dt2.Columns.Count
dt2.Columns.Add(dt1.Columns(i).ColumnName, GetType(Integer))

i2 = 0
Do Until i2 = dt2.Rows.Count
dt2.Rows(i2)(Colinx) = dt1.Rows(i2)(i)
i2 = i2 + 1
Loop

End If
i = i + 1
Loop

SQL database datatable : Use select into statement....

.net Datatable Object : (I am assuming you have all key from dt1 in dt2)

    dtresult = dt1.Copy

    Dim ds As New DataSet
    ds.Tables.Add(dtresult )
    ds.Tables.Add(dt2)
    ds.Relations.Add("KeyRelation", dt2.Columns("Key"), dtresult .Columns("Key"))

    dtresult .Columns.Add("OTS2", System.Type.GetType("System.Int32"), "Parent.OTS2")
    dtresult .Columns.Add("OTS3", System.Type.GetType("System.Int32"), "Parent.OTS3")


    dtresult.AcceptChanges()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM