If you have ever tried to delete alot of items in a SharePoint list (programatically) you will realise that this can be very time consuming (by the server) as it needs to iterate over EVERY object in the item collection and delete the list items one by one – that is if you use the standard SharePoint API. Luckily there is ProcessBatchData method available on the SPWeb item which allows you to do batch processing on particular methods in SharePoint – and deleting items in a list is a perfect candidate for this.
Basically all you need to do is pass an XML packet to the ProcessBatchData method which gives it the instructions on what to do. In this case we are using the Delete command.
On the MSDN code gallery there is already an implementation of this, however I changed this myself so that I could change it and use it as a single method in a utility class. In the end the method I ended up with is:
public
static void DeleteAllItems(SPWeb currentWeb, SPList currentList){
StringBuilder sbDelete = new StringBuilder();
sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
string command = "<Method><SetList Scope=\"Request\">" + currentList.ID +"</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";
foreach (SPListItem item in currentList.Items)
{
sbDelete.Append(string.Format(command, item.ID.ToString()));
}
sbDelete.Append("</Batch>");
currentWeb.ProcessBatchData(sbDelete.ToString());
}
All you need to do now is pass in the current SPWeb (eg SPContext.Current.Web) and the current list object, then call this method and all your list items will be nicely deleted!