I ran across a really helpful link the other day for a common SharePoint development task...deleting all items from a SharePoint list.  You can read the full article here, as well as the full code over on MSDN Code Gallery

As the posting states, the advantage of the method below is that you pass an XML string batch to the site to have the items deleted, essentially making only 1 connection the server.  Iterating over each list item and deleting them individually would essentially make calls to the server on every delete.

For the sake of this blog posting/historical purposes, I've included the code below to help explain it.

 

   1:  StringBuilder sbDelete = new StringBuilder();
   2:   
   3:  sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
   4:   
   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:   
  13:  sbDelete.Append("</Batch>");
  14:   
  15:  spSite.RootWeb.ProcessBatchData(sbDelete.ToString());

 

What I really like about this code is its simplicity, but also provides the ability to do some add conditions inside the foreach loop, and test for certain values.  This way, you could delete say, all items with a date of 1/1/2007. 

A few things to note after reading the posting and its comments.

All items that get deleted from this method go into the Recycle Bin which is important to remember.  To COMPLETELY get rid of the items, use the code above then also call the delete method of the Recycle Bin from your SPWeb object ( mySpWeb.RecycleBin.DeleteAll(); )

Another option, which is a tad less flexible, but does essentially the same, is to switch a list to data view mode, which turns it into an excel like spreadsheet where you can highlight all the rows and delete them that way.

 

Needless to say, the options above are better then just iterating through all the items in the list and calling delete.


Posted in: Sharepoint  Tags: ,
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017 Tony Testa's World