Web Code Blog

A web repository of coding tips and knowledge base articles

Archive for June, 2010

Removing objects while iterating through collections

Posted by Stefan Zvonar on June 30, 2010

Here is a quick little tip ….

If you need to iterate through a collection of some sort and delete items as you go, you will not be able to remove the object while moving forward through the collection.  The answer?  Go backwards!  Here is an example:

        For Each table As DataTable In myDataSet.Tables()
            ' Loop backwards so that we can remove the column without interfering with our iteration
            For i As Integer = table.Columns.Count - 1 To 0 Step -1
                ' Enter your own checks here
                table.Columns.RemoveAt(i)
            Next
        Next

Hope this helps,

Stefan.

For more Web Code, ASP.NET, SQL Server and other development tips, please check back here at webcodeblog.com often.

Posted in .NET | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.