1

我在这里所做的是在数组列表和字典中保存两列的表。

Dim result As New ArrayList()
While dr.Read()
        ' Insert each column into a dictionary
        Dim dict As New Dictionary(Of String, Object)
        For count As Integer = 0 To (dr.FieldCount - 1)
            dict.Add(dr.GetName(count), dr(count))
        Next
        ' Add the dictionary to the ArrayList
        result.Add(dict)
    End While

.........现在我想检查它,当它找到时 - 删除它。因为有很多数据,所以可以节省时间。我收到错误“集合已修改;枚举操作可能无法执行。” 删除后进入下一步。我理解这个问题,但我该如何克服这个问题?如何将其转换为带删除的循环?

For Each dat As Dictionary(Of String, Object) In result 
                        comp2 = dat("ID") 
                        If comp2 = comp Then
                            advcode = advcode & "," & dat("ADVC")
                            found = True
                            firstattempt = False
                            result.Remove(dat)
                        Else
                            If found And Not firstattempt Then Exit For
                        End If
                    Next
4

3 回答 3

2

你为什么不使用 aList(Of Dictionary(Of String, Object))而不是 a ArrayList?这将使代码更清晰。

尽管如此,只需将集合复制到新集合中,因此从原始集合中删除元素不会停止副本的迭代:

For Each dat As Dictionary(Of String, Object) In result.ToArray() ' Copy into new array '
    comp2 = dat("ID") 
    If comp2 = comp Then
        advcode = advcode & "," & dat("ADVC")
        found = True
        firstattempt = False
        result.Remove(dat)
    Else
        If found And Not firstattempt Then Exit For
    End If
Next
于 2013-09-05T07:10:35.753 回答
1

通常有两种修复方法:

  1. 从后面遍历arraylist:

    For i As Integer = result.Count - 1 To 0 Step -1
        Dim dat = CType(result(i), Dictionary(Of String, Object))
        ' ...
        ' if found:
        result.RemoveAt(i)
    Next
    
  2. 将 arraylist 复制到一个新数组:

    For Each Dat As Dictionary(Of String, Object) In result.ToArray()
        ' do your stuff here
    Next
    

选项 1 应该提供更好的性能

于 2013-09-05T07:11:24.460 回答
1

尝试这个:

Dim iCont As Integer = 0

While result.Count > iCont
    Dim dat As Dictionary(Of String, Object) = CType(result(iCont), Dictionary(Of String, Object))
    comp2 = dat("ID") 
    If comp2 = comp Then
        advcode = advcode & "," & dat("ADVC")
        found = True
        firstattempt = False
        result.Remove(dat)
    Else
        If found And Not firstattempt Then Exit For
        iCont += 1
    End If   
End While
于 2013-09-05T07:14:18.837 回答