01 Dec

Collection was modified; enumeration operation may not execute

Collection was modified; enumeration operation may not execute

This exception is thrown when you are trying to delete items of a collection in a for loop or using a for each loop.

The ideal solution could be to use a for loop with a descending counter.

Problem:

for e.g.

If suppose you are executing any of following code snippets

1.

for (int listcounter = 0; listcounter < ReferenceOwnersList.Items.Count; listcounter++)
{
ReferenceOwnersList.Items.Delete(0);
}

2.

foreach (SPListItem Li in ReferenceOwnersList.Items)
{
Li.Delete();
}

Here ReferenceOwnersList is a collection.

Now whenever this code will execute for the first time, the number of items reduce. So the second item gets the first index.
I tried deleting 0th item everytime but still I got the exception. Again changing index may cause skipping the items in most senerios.

And the collection throws the “Collection was modified; enumeration operation may not execute” exception.

Solution:

Solution
Use a reducing for loop.

for (int cntLi = ReferenceOwnersList.Items.Count – 1; cntLi >=0 ;cntLi — )
{
ReferenceOwnersList.Items.Delete(cntLi);
}

so that even if the last item is deleted, the index of other items wont change.

3 Responses to “Collection was modified; enumeration operation may not execute”

  1. 1
    IDEOBEHOK Says:

    Hello, I can’t understand how to add your blog in my rss reader
    ————————

  2. 2
    Jayvardhan Patil Says:

    hi,

    use following link for my RSS

    http://codeforfuture.com/feed/

  3. 3
    hoilsagossy Says:

    great domain name for blog like this)))
    ————————

Leave a Reply