在DataTable中添加行

时间:2016-04-21 01:42:37

标签: vb.net datatable

我在vb中正在做一个项目,我正在尝试将 dataTable name dt中的所有行添加到新的dataTable名称dtNew ,但我不希望在dtNew中添加重复行添加计数如果重复。有人帮我请。

这是一个示例 dataTable name dt ,您可以看到 apple is duplicate

Sample dataTable

这是我的代码。

Dim dtNew As DataTable = New DataTable '---> I Created new DataTable

    '---> Created 3 columns
    dtNew.Columns.Add("TYPE", Type.GetType("System.String"))
    dtNew.Columns.Add("NAME", Type.GetType("System.String"))
    dtNew.Columns.Add("COUNT", Type.GetType("System.Int32"))

    For Each dtRow As DataRow In dt.Rows ' ---> loop all the rows in dt DataTable
        Dim newRow As DataRow = dtNew.NewRow
        newRow("TYPE") = dtRow("TYPE")
        newRow("NAME") = dtRow("NAME")
        newRow("COUNT") = dtRow("COUNT")

        'check if dtNew DataTable has no row
        If Not dtNew Is Nothing AndAlso dtNew.Rows.Count = 0 Then
            'add new row
            dtNew.Rows.Add(newRow)
        Else

            ' I want to check first all the rows in dtNew DataTable 
            ' if its existed, and if it's not then add new row
            For Each dtNewRow As DataRow In dtNew.Rows
                If ((dtNewRow("TYPE") = "VEGETABLE" OrElse _
                    dtNewRow("TYPE") = "FRUIT") And _
                    dtNewRow("NAME") <> newRow("NAME")) Then

                    'insert row
                    dtNew.Rows.InsertAt(newRow, dtNew.Rows.Count)
                    'error: Collection was modified; enumeration operation might not be executed.

                End If
            Next
        End If
    Next

1 个答案:

答案 0 :(得分:1)

For Each row As DataRow In dt.Rows
    Dim type = CStr(row("Type"))
    Dim name = CStr(row("Name"))
    Dim existingRows = dtNew.Select(String.Format("Type = '{0}' AND Name = '{1}'",
                                                  type,
                                                  name))

    If existingRows.Length = 0 Then
        'No match so create a new row.
        Dim newRow = dtNew.NewRow()

        newRow("Type") = type
        newRow("Name") = name
        newRow("Count") = row("Count")

        dtNew.Rows.Add(newRow)
    Else
        'Match found so update existing row.
        Dim newRow = existingRows(0)

        newRow("Count") = CInt(newRow("Count")) + CInt(row("Count"))
    End If
Next

由于表具有相同的模式,您甚至可以将If块简化为:

dtNew.ImportRow(row)

如果row除了RowState之外有Unchanged并且你也不想导入它,那只会是一个问题。