Search:

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;
if(!File.Exists(location)){
listToDelete.Add(e);
}

}
foreach (Element e in listToDelete) {
listAll.Remove
(e);
}

}

2 comments:

Mario said...

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

Luís said...

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

http://msdn.microsoft.com/en-us/library/wdka673a.aspx