Search code examples
c#loopsenumerator

Enumerator problem, Any way to avoid two loops?


I have a third party api, which has a class that returns an enumerator for different items in the class.

I need to remove an item in that enumerator, so I cannot use "for each". Only option I can think of is to get the count by iterating over the enum and then run a normal for loop to remove the items.

Anyone know of a way to avoid the two loops?

Thanks

[update] sorry for the confusion but Andrey below in comments is right.

Here is some pseudo code out of my head that won't work and for which I am looking a solution which won't involve two loops but I guess it's not possible:

for each (myProperty in MyProperty)
{
if (checking some criteria here)
   MyProperty.Remove(myProperty)
}

MyProperty is the third party class that implements the enumerator and the remove method.


Solution

  • Common pattern is to do something like this:

    List<Item> forDeletion = new List<Item>();
    
    foreach (Item i in somelist)
       if (condition for deletion) forDeletion.Add(i);
    
    foreach (Item i in forDeletion)
       somelist.Remove(i); //or how do you delete items