简体   繁体   中英

Error when looping through datatable

In my program I loop through records on an excel file to create a datatable. Then I need to do some additional data maintenance that I cannot do in the first loop.

I am trying to figure out the best way to loop through the existing datatable to remove rows with duplicate values while keeping others.

On my example table, I have three columns. For each CompanyCode I need to remove the BillingItems that are duplicates AND keep the FeeAmount that is the highest. So, for CompanyCode 1234, we would need to remove the first and second rows, and keep the fourth.

These values are not always going to be in the same order.

+-------------+-----------+-------------+
| CompanyCode | FeeAmount | BillingItem |
+-------------+-----------+-------------+
|        1234 |        10 | A           |
|        1234 |        10 | A           |
|        1234 |        15 | B           |
|        1234 |        20 | A           |
|        9876 |        10 | A           |
|        9876 |        20 | B           |
|        9876 |        30 | A           |
|        9876 |        30 | A           |
+-------------+-----------+-------------+

When I get into the loop, I receive the error: "Collection was modified; enumeration operation might not execute." Below is my code for the loop.

For Each loRow In dt.Rows

    Dim liDupeCount As Integer = 0
    liCompanyCode = loRow(0)
    ldFeeAmount = loRow(1)
    lsBillingItem = loRow(2)

    Dim dupeFeeAmounts() As DataRow = dt.Select("CompanyCode = '" & liCompanyCode & "' and FeeAmount = '" & ldFeeAmount & "' and BillingItem = '" & lsBillingItem.Replace("'", "''") & "'")

    For Each row As DataRow In dupeFeeAmounts
        liDupeCount += 1
    Next

    If liDupeCount > 1 Then
        dt.Rows(liRowCount).Delete()
    End If      
    liRowCount += 1

Next

You can't delete the rows inside the loop where you are using datatable for iteration and deleting the same table rows causes collection error,

loop concentrates on the number of rows of datatable while starting loop, if you delete rows the then number of rows decreases and mis-match with loop concentrating count and datatable count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM