G
Guest
This is a little problem that has been driving me nuts. I have an ArrayList
of objects, and I want to delete all the objects that satisfy some condition:
foreach (MyObject myObject in ObjectList)
{
if (MyObject.DeleteCondition())
{
ObjectList.Remove(myObject);
}
}
This of course doesn't work because the deletion messes up the iteration and
an exception is thrown. The only way I've managed to do this is:
ArrayList ToBeDeleted = new ArrayList();
foreach (MyObject myObject in ObjectList)
{
if (MyObject.DeleteCondition())
{
ToBeDeleted.Add(myObject);
}
}
foreach (MyObject myObject in ToBeDeleted)
{
ObjectList.Remove(myObject);
}
This seems awfully ham-fisted and I can't help thinking there must be a more
elegant way of doing it. Any suggestions?
of objects, and I want to delete all the objects that satisfy some condition:
foreach (MyObject myObject in ObjectList)
{
if (MyObject.DeleteCondition())
{
ObjectList.Remove(myObject);
}
}
This of course doesn't work because the deletion messes up the iteration and
an exception is thrown. The only way I've managed to do this is:
ArrayList ToBeDeleted = new ArrayList();
foreach (MyObject myObject in ObjectList)
{
if (MyObject.DeleteCondition())
{
ToBeDeleted.Add(myObject);
}
}
foreach (MyObject myObject in ToBeDeleted)
{
ObjectList.Remove(myObject);
}
This seems awfully ham-fisted and I can't help thinking there must be a more
elegant way of doing it. Any suggestions?