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);
}
}