Skip to content

August 22, 2010

Calling Remove From For Each Loop in .NET

I recently had this problem where I needed to do something to all the items of a certain type in a collection, remove them and continue through what was left.

This error was the result of my endeavors:
System.InvalidOperationException: Collection was modified; enumeration operation might not execute.

I wasn’t looking for lengthy writeups so here’s the code:

Before With For Loop:

   1:  Dim curLst As List(Of String)
   2:   
   3:  For Each item As String In BigStringLst
   4:   
   5:      curLst = BigStringLst.FindAll(AddressOf FindResult)
   6:   
   7:      ' DO SOMETHING WITH YOUR LIST OF STRINGS
   8:      ' AND THE CURRENT ITEM
   9:   
  10:      BigStringLst.RemoveAll(AddressOf FindResult)
  11:   Next

What you’re actually looking to do is use a While loop and remove the items. So while you still have items you want to keep processing. The “Next” item is simply the first item in the collection since the collection is shrinking.

After with While Loop:

   1:  Dim curLst as List(Of String)
   2:   
   3:  While BigStringLst.Count > 0
   4:     Dim item As String = upcLst(0)
   5:   
   6:     curLst = BigStringLst.FindAll(AddressOf FindResult)
   7:   
   8:     ' DO SOMETHING WITH YOUR LIST OF STRINGS
   9:   
  10:     BigStringLst.RemoveAll(AddressOf FindResult)
  11:   
  12:  End While
  13:   

Here is the code for the predicate function used in FindAll and RemoveAll for the List(Of String):

  1:  Private Function FindResult(ByVal item As String) As Boolean
  2:     Return (item = "virtualadrian.com")
  3:  End Function

This code was done for folks that want VB.NET so if you want to get this in C# just use a converter. I prefer this one :

http://www.developerfusion.com/tools/convert/vb-to-csharp/

PS: Obviously I wasn’t searching for strings or doing the simple stuff the example shows. However you should get the idea. Also I wrote this up in Notepad so.. watch for syntax errors :0)

Good Luck !

Read more from ASP.NET

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments