page 1 of 1
Comments: 8 | Views: 727
mVPstar
mVPstar
I'm white because I smelt an onion.
Alright...

I'm trying to iterate through a list, and for each item I'm iterating through another list. Based on certain conditions, I want to add the item to another collection. The problem is, whenever I add it, the initial collection empties out.

Here's a code snippet of what I'm doing:


for (int i = _tempMedia.Count - 1; i >= 0; i--) // Looping through initial collection

{

T mediaItem = _tempMedia[i];

    for(int j = mediaItem.MetaTags.Count - 1; j>=0; j--) //Looping through a List<string> in the current item of initial collection

    {

        string tag = mediaItem.MetaTags[j];

        if (_currentGallery.HasAlbum(tag))

        {

        _currentGallery.Albums[tag].Add(mediaItem); //Add item to second collection

        }
    }
}
 



Basically, after the item gets added the first time, collection _tempMedia empties out completely, thereby throwin an "Index out of range" error on the next iteration. I had foreach loops before but kept getting "Collection was modified; enumeration operation may not execute." errors. I replaced them with for loops after googling for a solution. Google says I should use the lock keyword, but I have no idea how to use it/if it'll actually work.

What should I do to retain the original collection so that I can iterate through all items and not just the first?

Thanks!

EDIT: SOLVED: http://channel9.msdn.com/forums/TechOff/418221-Collection-disappearing-when-adding-items-into-another-collection-via-a-for-loop/?CommentID=418327
staceyw
staceyw
Before C# there was darkness...
Debug the collection length before and after the "T mediaItem = tempMedia[i];" line to see if for some reason the collection is popping and causing the 1 off error.  Why are you enumerating in reverse instead of forward?  Some logic requirement?
figuerres
figuerres
???
what kind of collection's are they?  is this a standard .net type ?

some collections only support forward iteration this may be one of them.

Don't remove items from a collection while iterating through it.
evildictaitor
evildictaitor
How could you use the adjective "indescribable" truthfully?
Simple hack to avoid the "don't modify a collection while using it":

Change code of the form:

ICollection<T> collection;

// wrong:
foreach(T f in collection){
  modify(f, collection);
}

// right
foreach(var f in new List<T>(collection)) {
  modify(f, collection);
}

note that this iterates over the initial state of the collection, so elements added to the collection during the loop won't get changed, and elements removed from the collection before their "turn" in the loop won't get removed from the iteration space.

If your collection supports it, a better way is

foreach(var f in collection.ToArray()){
  modify(f, collection);
}

which is slightly faster.