I have this function for removing duplicates in arrays:
Function remove_duplicates(array)
Dim dup_count As Integer = 0
For Each element As String In array
For Each inner_element As String In array
If (element = inner_element) Then
If (dup_count = 0) Then
dup_count = 1
Else
array.Remove(inner_element)
End If
End If
Next 'dies here
dup_count = 0
Next
Return array
End Function
Into which I am feeding the following test arrayList:
(0) test1
(1) test2
(2) test3
(3) test2
Which I expect to return:
(0) test1
(1) test3
(2) test2
What is happening at the moment is that the inner loop reaches the array.Remove(inner_element) line for the first time in its second loop during the second loop of the main foreach, reaches the inner next line and then just stops executing. There are no warnings / notices, the debugging step though just ends as if there was no further logic.
Can anyone suggest a work around or why this is happening?
You cannot modify a list that you are currently iterating over.
Furthermore, there are better ways of removing from a list using the
RemoveAllmethod:This requires the Linq method
Count(henceImport System.Linq).EDIT
Rather than doing this manually, it’s of course better, more readable and more efficient to resort to pre-existing methods:
Distinctinternally constructs aHashSetwhich makes this method run in asymptotic time O(n) rather than O(n^2) (which is the runtime of the above method).