0

I am comparing two arrays, if the first array contains a word in the second array then it should delete it from the first array.

For Each word In array1
    If array2.Contains(word) Then
        array1.Remove(word)
    End If
Next

However when I debug it gives me the following error:

Collection was modified; enumeration operation may not execute.

because its updating the array while its trying to iterate through it

Sarvesh Mishra
  • 2,014
  • 15
  • 30
Dman
  • 553
  • 1
  • 11
  • 33

2 Answers2

1

Using Linq it could look like this. It filteres array1 by array2 and returns new array which contains only items from array1 which are not found in array2.

Public Function FilterArrayByArray() As String()
    Dim array1() = New String() {"word1", "word2", "word3", "word4", "word5"}
    Dim array2() = New String() {"word2", "word5"}

    Return array1.Where(Function(array1Item) Not array2.Contains(array1Item)).ToArray()
End Function
Daniel Dušek
  • 13,683
  • 5
  • 36
  • 51
0

I've seen this problem in C# before, assuming it's the same kind. In your example you are using a for each loop. Switch to a for loop (which has an index).

When a word is found that containsarray2.Contains(word), subtract one from the index.

E.G (C#),

for (int i = 0; i < array1.Count; i++) //iterate through the items in array1
{
    if (array2.Contains(word) //if array2 contains word, ...
    {
        array1.Remove(word); //... then remove it, and subtract from i.
        i--;
    }
}

That or iterate through array1 backwards doing --i above. Both work fine.

Shyy Guy
  • 232
  • 3
  • 18