Custom Search

Monday, April 28, 2008

Deleting elements from a list while iterating

In C# you are not allowed to iterate and delete elements from a list at the same time. So what you need to do is to find a way to delete these elements later, after knowing what you are going to eliminate. In C++ you won’t have this problem but in C# an exception will be triggered.

This example below demonstrates how to solve this nicely. Basically what it does is that looks for none existing files from your hard drive and saves these on a separate List. Suppose that the object Element contains a string value representing a file path:

public void validateList() {

//New list that will contain the Objects to be deleted later on.
List<Element> listToDelete = new List<Element>();

//ListAll contains all the Element objects
foreach (Element e in listAll()) {
string location = e.loc;

foreach (Element e in listToDelete) {



Mario said...

You know, that is an absolutely awesome article. Major props!!

IrĂ³nico said...

You can also try the RemoveAll method, which uses a predicate to delete elements from a list.