Solved

Collection was modified; enumeration operation may not execute, enumerating through FileInfo

Posted on 2009-05-20
9
1,266 Views
Last Modified: 2013-12-17
I have a collection of zipfiles in a FileInfo object, and as I loop through them, I determine if I need it or not. When I run the code, I get following runtime error message...

Collection was modified; enumeration operation may not execute

Here is a sample pseudo, of what I have going on. Is there a simple way to work around this without making things too hairy?  :-)
foreach (FileInfo zp in ZipFiles)
            {
			
					// Do some calculations. Determine if I don't need the zip file.
                    ZipFiles.Remove(zp);//remove zipfiles that I don't need
					
					// Do some calculations. Determine if I do need the zip file.
                    ZipFiles.Add(fi);//add some new zipfiles that I do need.
					
 
            }//end of foreach loop

Open in new window

0
Comment
Question by:silentthread2k
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 11

Assisted Solution

by:srikanthreddyn143
srikanthreddyn143 earned 50 total points
ID: 24433460
You cant add or remove from a collection while doing a loop on it. You have to clone that collection and make add/remove on it.
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 200 total points
ID: 24433501
You cannot modify a list (ZipFiles) for which you are stepping through via an iterator. Try copying the list and modifying the copy.
public List<FileInfo> EditList(List<FileInfo> ZipFiles)
{
    List<FileInfo> tempList = new List<FileInfo>(ZipFiles);
 
    foreach (FileInfo zp in ZipFiles)
    {
        // Do some calculations. Determine if I don't need the zip file.
        tempList.Remove(zp);//remove zipfiles that I don't need
 
        // Do some calculations. Determine if I do need the zip file.
        tempList.Add(fi);//add some new zipfiles that I do need.
    }
 
    return tempList;
}

Open in new window

0
 
LVL 26

Assisted Solution

by:Anurag Thakur
Anurag Thakur earned 50 total points
ID: 24433821
to modify a collection you cannot use a foreach loop as if you remove the collection the indexers will be modified and and exception will be thrown

to achieve use a for loop and start from the last (highest count) and come back to 0 and if your calculations prove that it needs to be removed then you can achieve it easily
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 3

Assisted Solution

by:mpf1748
mpf1748 earned 100 total points
ID: 24433912
Another way that I have used in the past is to traverse the list backwards and remove as a I go, but you will have to use a for loop instead of a foreach loop. This solution works better for removing, but you could also add items at the end of the list.
for (int i = ZipFiles.Count-1; i >= 0; i--)
{
  FileInfo zf = ZipFiles[i];
  if (<logic to remove>)
  {
    ZipFiles.Remove(zp);
  }
  if (<logic to add>)
  {
    ZipFiles.Add(<new zip file>);
  }
}

Open in new window

0
 
LVL 22

Assisted Solution

by:p_davis
p_davis earned 100 total points
ID: 24434135
you can use a foreach with a delegate

ZipFiles.ForEach(delegate (FileInfo zp)
            {
                       
                                        // Do some calculations. Determine if I don't need the zip file.
                    ZipFiles.Remove(zp);//remove zipfiles that I don't need
                                       
                                        // Do some calculations. Determine if I do need the zip file.
                    ZipFiles.Add(fi);//add some new zipfiles that I do need.
                                       
 
            });
//end of foreach loop
0
 
LVL 22

Expert Comment

by:p_davis
ID: 24434148
i really wouldn't recommend removing or adding in a for loop though
0
 

Accepted Solution

by:
silentthread2k earned 0 total points
ID: 24434197
Thanks, I will just modify the files and then just build the collection.
0
 

Author Comment

by:silentthread2k
ID: 24434217
Thanks.
0
 

Author Comment

by:silentthread2k
ID: 24434613
I accepted my solution, but let me know if you get awarded points, which is what I tried doing.
Thanks again.
0

Featured Post

Is Your Team Achieving Their Full Potential?

74% of employees feel they are not achieving their full potential. With Linux Academy, not only will you strengthen your team's core competencies but also their knowledge of of the newest IT topics.

With new material every week, we'll make sure that you stay ahead of the game.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question