Thursday, February 24, 2011

Collection was modified enumeration operation may not execute

Scenario:
I was writing a small SharePoint utility and was in rush for my next meeting.
When I ran my utility to test the first cut. I got the following error.

Error : [System.InvalidOperationException] = {"Collection was modified; enumeration operation may not execute."}

Code was like this

 foreach (SPListItem item in sourceList.Items)
{
if(item["Title"]!="blah")
{
item["Title"] = "blah blah blah ";
// Some more code
item.Update();
}
}
Reason:
While the error message is pretty clear and is not specific to SharePoint, I thought of posting. As you see I am looping through the ListItem Collection and modified the item itself which re-arranged the Collection itself. So next time SharePoint loop to get next item, you will encounter the above error.

Solution:
There can be 'n' solutions for this but this is what I did to fix it.
While looping I didn't modify the item but only copied its ID in a List and added an extra looping to get the items by ID and then modify the Item.

Modified Code:
 List<int> itemIDs = new List<int>();
foreach (SPListItem item in sourceList.Items)
{
if(item["Title"]!="blah")
{
itemIDs.Add(listItem.ID);
}
}

foreach (int i in itemIDs)
{
item["Title"] = "blah blah blah ";
// Some more code
item.Update();
}

2 comments:

zara February 24, 2011 at 6:43 AM  

There are certainly a lot more details to take into consideration, but thanks for sharing this post. In Microsoft Office and SharePoint 2010, many of Google's features are in effect mimicked while maintaining consistency enough for continued business use.

Anonymous,  January 11, 2013 at 12:45 PM  

Your second "for" loop will error out. Also, don't see where you are using the int "i", when looping thru itemIDs.