RobVious
RobVious

Reputation: 12925

Possible to modify a List while iterating through it?

I have the following:

foreach (var depthCard in depthCards)
{
    var card = InternalGetCard(db, depthCard.CardId);
    var set = InternalGetSet(db, (int)card.ParentSetId);
    var depthArray = InternalGetDepthArrayForCard(db, set.SetId);
    foreach (var cardToUpdate in set.Cards)
    {
        // do stuff
        SaveChanges(db);
        // since I already took care of it here, remove from depthCards
        depthCards.Remove(depthCardToUpdate);
    }
}

This isn't working though because I'm modifying the collection in the middle of a loop. Is there some type of collection that does allow this type of access?

I don't want to ToList() the depthCards because I already have them and I want to modify that list as I'm iterating. Is this possible?

Upvotes: 18

Views: 20557

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460208

You can iterate backwards with a for-loop

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

or if you just want to remove items on a condition, use List.RemoveAll:

depthCardToUpdate.RemoveAll(dc => conditionHere);

Upvotes: 8

Óscar López
Óscar López

Reputation: 236104

It's possible, the trick is to iterate backwards:

for (int i = depthCards.Count - 1; i >= 0; i--) {
  if (depthCards[i] == something) { // condition to remove element, if applicable
     depthCards.RemoveAt(i);
  }
}

Upvotes: 36

Haney
Haney

Reputation: 34852

You can create a custom enumerator that handles this for you. I did this once and it was a bit tricky but worked after some finesse.

See: http://www.codeproject.com/Articles/28963/Custom-Enumerators

Upvotes: 1

Related Questions