Is it possible to change a list during iteration 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); depthCards.Remove(depthCardToUpdate); // since I already took care of it here, remove from depthCards } } 

This does not work though, because I am changing the collection in the middle of a loop. My question is ... is there some kind of collection that permits this type of access?

I do not want ToList() depthCards because I already have it and I want to change this list during iteration. Is it possible?

+10
c #
source share
3 answers

Perhaps the trick is to repeat the iteration back:

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

You can do the repetition with for -loop

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

You can also use List.ForEach , which allows you to change the list in an iteration:

 depthCardToUpdate.ForEach(dc => depthCardToUpdate.Remove(dc)); 

or if you just want to remove items provided use List.RemoveAll :

 depthCardToUpdate.RemoveAll(dc => conditionHere); 
+7
source share

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

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

+1
source share

All Articles