简体   繁体   中英

Collection was modified error when looping through list and removing items

I have the following:

 tempLabID = lstLab;
                    foreach (string labID in lstLab)
                    {
                        if (fr.GetFileRecipients(fsID).Contains(labID))
                        {
                            tempLabID.Remove(labID);
                        }
                    }   

When I debug and watch lstLab and I get to tempLabID.remove() it changes lstLab to 0 from 1, and then in turn, when it gets back to the foreach I get an error saying the collection has been modified.

I can't understand why it's happening. I am modifying a different collection.

No, you are modifying the same collection. You have two variables pointing to the same collection. Your first line needs to clone the collection for it to work.

You can modify your code so that you don't have that problem:

lstLab.RemoveAll( labID => fr.GetFileRecipients(fsID).Contains(labID) );

This will remove all those you want to remove, without the need for loops or temp copies.

you can't do that.

change the

tempLabID = lstlab;

to

tempLabID = lstLab.ToList();

You're not modifying a different collection since both tempLabID and lstLab are pointing to the same collection.

Try:

tempLabID = lstLab.ToList();

You are modifying the same collection because tempLabID = lstLab copy the reference (pointer) to the collection, but it doesn't clone the collection.

You probably want to clone the collection:

tempLabID = lstLab.ToArray();

This will solve your problem:

tempLabID = lstLab.Where(l => fr.GetFileRecipients(fsID).Contains(l)).ToList();

For further explanation read Jon Skeets answer

In this situation, I usually just loop through the list backwards. (Not very fancy but it works.)

    for (int x = lstLab.Count - 1; x >= 0; x--)
    {
        string labId = lstLab[x];
        if (fr.GetFileRecipients(fsID).Contains(labID))        
           lstLab.RemoveAt(x);        
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM