在数据表中添加行

杰罗布·伯纳多

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

这是一个示例数据表名称dt,如您所见,苹果是重复的

样本数据表

这是我的代码。

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
金西尼
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你不想导入了。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章