O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Remove Items While Iterating Through a Collection

Problem

You need to search for items and delete them. However, you can’t delete items while iterating through a collection.

Solution

Add the items that you want to delete to another collection. Then iterate through this collection and remove all items from the original collection.

Discussion

Enumerating through a collection is strictly a read-only operation. However, you can enumerate through a collection to find the items you need to remove, and then delete them in a second step, as shown below.

Dim List As New ArrayList() List.Add("This") List.Add("is") List.Add("a") List.Add("simple") List.Add("test") ' Mark words that start with "t" for deletion. Dim ItemsToDelete As New ArrayList() Dim Item As String ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required