简体   繁体   English

遍历数据表时出错

[英]Error when looping through datatable

In my program I loop through records on an excel file to create a datatable. 在我的程序中,我遍历excel文件中的记录以创建数据表。 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. 对于每个公司代码,我需要删除重复的BillingItem,并保持FeeAmount为最高。 So, for CompanyCode 1234, we would need to remove the first and second rows, and keep the fourth. 因此,对于CompanyCode 1234,我们需要删除第一行和第二行,并保留第四行。

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, 您无法删除使用datatable进行迭代的循环内的行,并且删除相同的表行会导致收集错误,

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. 循环在启动循环时将重点放在数据表的行数上,如果删除行,则行数会减少,并且与循环集中计数和数据表计数不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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