0

我发现使用参考数据表将数据表转换为新数据表有困难。我的问题令人困惑,我不擅长解释事情,所以我画了一张照片(见下文)。

我在内存上有两个数据表,我需要使用第二个映射表创建第三个数据表以供参考。列名只是举例,不能硬编码。

希望可以有人帮帮我。非常感谢。

在此处输入图像描述

4

2 回答 2

1

这可能不是最优化的代码,但它似乎工作......基本上使用映射表的“新列”列中的列名创建一个新的数据表,然后对于第一个表中的每一行,逐步执行映射表,将“旧列”列的值存储在“新列”列中

Protected Sub MapData()

    Dim table1 = New DataTable()
    Dim table2 = New DataTable()
    Dim table3 = New DataTable()

    With table1
        .Columns.Add("Fore Name")
        .Columns.Add("Sir Name")
        .Columns.Add("Date of Birth")
        .Columns.Add("Country")

        Dim newRow = .NewRow()
        newRow("Fore Name") = "AA"
        newRow("Sir Name") = "AA"
        newRow("Date of Birth") = "01.01.1999"
        newRow("Country") = "UK"
        .Rows.Add(newRow)
        ' etc
    End With

    With table2
        .Columns.Add("Old Columns")
        .Columns.Add("New Columns")

        Dim newRow = .NewRow()
        newRow("Old Columns") = "Fore Name"
        newRow("New Columns") = "First Name"
        .Rows.Add(newRow)

        newRow = .NewRow()
        newRow("Old Columns") = "Sir Name"
        newRow("New Columns") = "Last Name"
        .Rows.Add(newRow)

        newRow = .NewRow()
        newRow("Old Columns") = "Date of Birth"
        newRow("New Columns") = "DOB"
        .Rows.Add(newRow)
    End With

    For Each rowData As DataRow In table2.Rows
        table3.Columns.Add(rowData("New Columns"))
    Next

    For Each table1Data As DataRow In table1.Rows
        Dim newRow = table3.NewRow()

        For Each rowMap As DataRow In table2.Rows
            newRow(rowMap("New Columns")) = table1Data(rowMap("Old Columns"))
        Next

        table3.Rows.Add(newRow)
    Next

End Sub
于 2012-04-26T13:58:48.290 回答
0

试试这个,但这是在 c# 中,你可以将它转换为 vb

targetTable.Columns["forename"].Caption = "First Name";// Rename the column
targetTable.Columns["SirName"].Caption = "Last Name";// Rename the column
targetTable.Columns["DateofBirth"].Caption = "DOB";// Rename the column
targetTable.Columns["country"].Table.Columns.Remove("country");//this will remove the column

//reorder column in case you need it
// targetTable.Columns["First Name"].SetOrdinal(0);
// targetTable.Columns["Last Name"].SetOrdinal(1);
// targetTable.Columns["DOB"].SetOrdinal(2);

// newtable =targettable.copy();// this will copy everthing to newtable  

让我知道它是否没有帮助

于 2012-04-26T13:38:10.577 回答