Wednesday, 6 May 2015

Collection was modified; enumeration operation may not execute.

This error was happened in my Asp.net c# project ,specifically in a for loop iterating through the contents in a list . 

My code something like this :

 foreach (RequestContent content in  Contents)
{
    do something 
}

I googled for this type of error and finally got a solution .

I changed the code to :
 foreach (RequestContent content in  Contents.ToList())
{
    do something 
}
 and it worked fine.

The issue was that Contents was getting modified inside the loop. Calling Contents.ToList() copies the values of Contents to a seperate list at the start of the loop .No one can access this list . so nothing can modify it inside the loop and it worked perfectly .




5 comments:


  1. Wow.. Thanks much for sharing.. My friend also recommended you so that i can have a helping hand to make my blog as effective as possible.

    SMO Services Chennai

    ReplyDelete
  2. I have own car so now I am back out there trying to show him how to do car repairs. Your blog is an excellent source of info, thanks.

    car cleaning services in mumbai

    ReplyDelete
  3. This blog is having the general information. Got a creative work and this is very different one.We have to develop our creativity mind.This blog helps for this. Thank you for this blog. This is very interesting and useful.
    Android Training in Chennai

    ReplyDelete
  4. This is a very interesting web page and I have enjoyed reading many of the articles and posts contained on the website, keep up the good work and hope to read some more interesting content in the future.
    RFID Solutions
    Athletic Management Software
    CCTV Camera Dealers in Chennai
    CCTV Camera Installation in Chennai

    ReplyDelete