Click here to Skip to main content
15,884,978 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
IEnumerable<string> imagesFileNames = FindImages(imagesFolder);
 foreach(string imageFileName in imagesFileNames)
            {
                //my code
                //IEnumerable<string> imagesFilesNames = FindImages(imagesFolder);
                // it doesn't work!!  
            }



I have a code like this. Can i update the IENumerable collection in foreach loop?


Thanks,


Dcan.
Posted
Comments
Sergey Alexandrovich Kryukov 28-Oct-12 21:37pm    
Bad idea. Better explain what do you want to achieve in turns of ultimate goals.

And what do you mean "not working". It does work, only it work exactly the way you programmed it, which might be not what you expected.
--SA

That's a really bad idea. You cannot change a collection in the middle of enumerating it. If you alter the collection itself you'll put the enumerator into an unknown state, thus invalidating it to the point where behavior cannot be predicted. The .NET Framework will usually throw an exception if you try this.

Based on the brief code snippet you posted, there is no reason for you to be calling FindImages inside the foreach loop that is already enumerating a collection of filenames.
 
Share this answer
 
Please see my comment to the question: you did not explain what's "not working"; and you did not explain what did you try to achieve. However, I hope, lust one note should make you understand everything in this weird situation: you have defined two completely different variables pointing to completely different and unrelated objects: on is imageFileNames before the loop, and another one inside loop, defining a new object in each cycle.

All you need to do is to think about it.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900