Enumerator problem, any way to avoid two loops?

I have a third-party api that has a class that returns an enumerator for different elements in the class.

I need to delete an item in this enumerator, so I cannot use "for each". The only option I can think of is to get an account, iterate over the listing, and then start a normal loop to remove the items.

Does anyone know how to avoid two loops?

thank

[update] sorry for the confusion, but Andrew is lower in the comments right.

Here is some kind of pseudo code from my head that will not work and for which I am looking for a solution that will not include two cycles, but I think this is impossible:

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

MyProperty is a third-party class that implements an enumerator and a delete method.

+3
11

- - :

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 
+6

, , .

+3

, :

for (int i = items.Count - 1; i >= 0; i--)
{
   items.RemoveAt(i);
}

.

+2

- :

      public IEnumerable<item> GetMyList()
    {
        foreach (var x in thirdParty )
        {
            if (x == ignore)
                continue;
            yield return x;
        }

    }
+2

, . , . :

foreach (var item in collection) {
    if (item.Equals(toRemove) {
        collection.Remove(toRemove);
        break;      // <== stop iterating!!
    }
}
+2

Enumerator. ( ) . , linq smth :

   YourEnumerationReturningFunction().Where(item => yourRemovalCriteria);
+1

API- API API, ?

IEnumerator<T> IEnumerable<T>, - , . , , , , . ( API , .)

IList<T> - , for , , . ( - - .)

+1

IEnumerator.Count() , - , , .

SJoerd, , .

0

- ..

 // you don't want 2 and 3
 IEnumerable<int> fromAPI = Enumerable.Range(0, 10);
 IEnumerable<int> result = fromAPI.Except(new[] { 2, 3 });
0

, ( API- , .)

foreach(var delItem in ThirdPartyContainer.Items
                       .Where(item=>ShouldIDeleteThis(item))
                       //or: .Where(ShouldIDeleteThis)
                       .ToArray()) {
    ThirdPartyContainer.Remove(delItem);
}

.ToArray() , , , foreach.

, , , , .

, , , " " ; , (, , ). , , - - , .ToArray() : -).

0

, .
reflection.modify.
.

0

Source: https://habr.com/ru/post/1750647/


All Articles