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 ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.