Tuesday, October 16, 2012

Good technique for programmatically deleting items from SharePoint collections

If you're attempting to delete items from a SharePoint collection (i.e. this could include containers such as lists, groups, document libraries, workflow collections, etc), you'll often encounter a situation where you'll need to iterate through a given collection in order to find the appropriate item (i.e. using a "for" or "foreach" loop) and then delete that specific item.  Now, if you happen delete an item from the collection while you're iterating through it, your code will thrown an error message that will stop the process dead in its tracks due to the fact that you've actually changed the contents of the collection while your also in the process of looping through the contents.  Here is an example scenario in which I'm attempting to remove a given task list called "Expired Items Tasks" from a site:

Incorrect Code:

foreach (SPList expiredItemTaskList in web.GetListsOfType(SPBaseType.GenericList))
{
    if (expiredItemTaskList.Title == "Expired Item Tasks")
    {
        expiredItemsTaskList.Delete();
    }
}


This code will throw an error (i.e. often times "Collection was modified; enumeration operation may not execute") on the next iteration of the loop that takes place after you're deleted the selected item and will stop the process dead in it's tracks.  For your code to properly handle this scenario, a good strategy will be to temporarily store the specific object(s) targeted for deletion in a generic list until you've completed iteration process.  Once you've completed your review of the collection, you can then delete those objects at your liesure:

Correct Code:

List<SPList> listsToDelete = new List<SPList>();
foreach (SPList expiredItemTaskList in web.GetListsOfType(SPBaseType.GenericList))
{
    if (expiredItemTaskList.Title == "Expired Item Tasks")
    {
        listsToDelete.Add(expiredItemTaskList);
    }
}

foreach (SPList expiredItemsTaskList in listsToDelete)
{
    expiredItemsTaskList.Delete();
}

Anyway, I've run into this scenario on many occasions with other .NET code; however, I've found this scenario to be more prevalent in SharePoint due to the fact that most objects contained within it are collections.  Hope this helps!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.