簡體   English   中英

在數據表中添加行

[英]Adding row in DataTable

我正在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具有未UnchangedRowState且您也不想導入該row這才是問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM