Search code examples
c#sharepoint-2007foreachsplist

Error collection is modified, cannot perform enumeration on sharepoint list


not sure why i get the above error, i know its because of UpdateWorkflowAssociation is inside the foreach but i need it that way A simple help will be highly appreciated

                        `siteName = "http://xyz";

                        newCleanupDays = 5;
                        assoCounter = 0;
                        using (wfSite = new SPSite(siteName))
                        {
                            using (wfWeb = wfSite.OpenWeb())
                            {

                               //wfList = wfWeb.Lists[libraryName];
                                SPListCollection collList = wfWeb.Lists; //Open Lists
                                SPWorkflowAssociation _wfAssociation = null;

                                foreach (SPList oList in collList)
                                {
                                    if (oList.WorkflowAssociations.Count > 0)
                                    {
                                        foreach (SPWorkflowAssociation a in oList.WorkflowAssociations)
                                        {
                                            if (a.Name != null || a.Name != string.Empty)
                                            {
                                                a.AutoCleanupDays = newCleanupDays;
                                                _wfAssociation = a;
                                                assoCounter++;
                                            }
                                            else
                                            {
                                                _wfAssociation = a;
                                            }

                                        }
                                        oList.UpdateWorkflowAssociation(_wfAssociation);
                                    }

                                }
                                System.Console.WriteLine("\n" + wfAssoName + ": " + assoCounter.ToString() + " workflow association(s) changed successfuly!\n");
                            }
                        }`

Solution

  • Instead of

    foreach (SPList oList in collList)
    

    simply write

    foreach (SPList oList in collList.ToList())
    

    That way you will iterate over a copy which is not modified during the iteration, but the real collection can be updated.