【问题标题】:Adding row in DataTable在数据表中添加行
【发布时间】:2016-04-21 01:42:36
【问题描述】:

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

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

这是我的代码。

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

【问题讨论】:

    标签: vb.net datatable


    【解决方案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 并且您不想也导入它时,这才是一个问题。

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多