如何在 .net 中合并(加入)数据表,其中行跨越多个数据表

How to merge (join) datatables in .net where rows span multiple datatables

我有多个数据表要连接在一起。行跨表而不是列。

这意味着 datatable1 可能有第 1、2、3 列,而 datatable2 可能有第 4、5、6 列。

我想将两者合并,以便 datatable1 具有第 1、2、3、4、5、6 列。

我觉得我已经阅读了很多示例,但仍然无法正常工作。

Private Sub mergeDataTables()
    Dim primaryKeyValue As Integer
    Dim tableIndex As Integer = 0
    For Each t As System.Data.DataTable In dataSet.Tables
        Dim pkColumn As New System.Data.DataColumn
        primaryKeyValue = 0

        'add column to house primary key and move it to the far left of the table
        pkColumn = t.Columns.Add()
        pkColumn.SetOrdinal(0)

        'populate the primary key column with unique values
        For Each r As System.Data.DataRow In t.Rows
            r(0) = primaryKeyValue
            primaryKeyValue += 1
        Next

        'set the primary key column as a primary key
        t.PrimaryKey = {t.Columns(0)}


        If tableIndex > 0 Then
            For col = 1 To t.Columns.Count - 1
                'assign unique column names to all columns but primary key column
                t.Columns(col).ColumnName = String.Format("{0}{1}", GetExcelColumnName(tableIndex), col) 'using getexcelcolumname for no other reason that to get a unique column name 1 = a 2 = b etc
            Next
            dataSet.Tables(0).Merge(t)
        End If

        tableIndex += 1
    Next
End Sub

试试这个 - 您需要传入包含源表的 DataSet 作为参数,并且各表中的列不能具有相同的名称:

    Private Sub mergeDataTables(ds As DataSet)

    Dim mergedTable As New DataTable("MergedData")

    mergedTable.Columns.Add("ID", System.Type.GetType(System.Int32))

    'Create the combined fields for the table
    For Each t As System.Data.DataTable In ds.Tables
        For Each col As DataColumn In t.Columns
            Dim newCol As New DataColumn(col.ColumnName, col.DataType)
            mergedTable.Columns.Add(newCol)
        Next
    Next

    Dim rowId As Integer = 0

    For Each row As DataRow In ds.Tables(0).Rows

        Dim newRow As DataRow = mergedTable.NewRow

        For Each col As DataColumn In mergedTable.Columns

            If col.ColumnName = "ID" Then
                newRow(col.ColumnName) = rowId
            Else
                For Each t As DataTable In ds.Tables

                    'This table has the column we need here
                    If t.Columns.Contains(col.ColumnName) Then
                        'Retrieve the corresponding data from the same row in the source table
                        newRow(col.ColumnName) = t.Rows(rowId)(col.ColumnName)
                        Exit For
                    End If
                Next
            End If

        Next

        mergedTable.Rows.Add(newRow)
        rowId += 1
    Next

End Sub