less than 1 minute read

If you want to delete or remove all the items in a SharePoint list you need to iterate through each item and perform a delete. Most of the examples on the web iterate through each item to do the delete. The problem there is that each delete action makes a request to the server and a huge list is going to take a long time. You could always delete the entire list and recreate it but that would mean recreating the structure as well as the guid being changed.

The better method would be to make a single request with all the delete commands batched together as shown in the code sample below.

   1: private static StringBuilder BuildBatchDeleteCommand(SPList spList)
   2: {
   3:     StringBuilder sbDelete = new StringBuilder();
   4:     sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
   5:     string command = "<Method><SetList Scope=\"Request\">" + spList.ID + 
   6:         "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";
   7:  
   8:     foreach (SPListItem item in spList.Items)
   9:     {
  10:         sbDelete.Append(string.Format(command, item.ID.ToString()));
  11:     }
  12:     sbDelete.Append("</Batch>");
  13:     return sbDelete;
  14: }

I've published a working solution on the MSDN Code Gallery at http://code.msdn.microsoft.com/SharePointListDelete.

Categories:

Updated: