HOME ABOUT
I AM HERE
Bookmark and Share

Delete all items in a SharePoint list more efficiently

May 24, 2009 09:43 by Aidan

One way to remove all items from a SharePoint list is to iterate through every item and call delete like this.

However, a more efficient way to clear down an entire list is to use the ProcessBatchData method like this:

private void deleteAllListItems(SPSite site, SPList list)

  StringBuilder sbDelete = new StringBuilder();

  sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");


  string command = "<Method><SetList Scope=\"Request\">" + list.ID + "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar     Name=\"Cmd\">Delete</SetVar></Method>";

  foreach (SPListItem item in list.Items)
  {
    sbDelete.Append(string.Format(command, item.ID.ToString()));
  }

  sbDelete.Append("</Batch>");

  site.RootWeb.ProcessBatchData(sbDelete.ToString());
}


Tags:
Categories:
Actions: E-mail | Permalink | Comments (2) | Comment RSSRSS comment feed

Comments

May 25. 2009 23:22

This code has memory leak... also I was wondering when can I use this.. i can delete the list itself and recreate it which will drop all the items in list anyway...

Sandeep

May 28. 2009 17:59

Sandeep, Thanks for your comment. You are correct that the SPObjects need to be correctly disposed of. This code example would require this to be done elsewhere.
You are correct that you could just delete the list itself and recreate it, this would do exactly the same thing. Although if keeping the list ID is important to your solution then that would not be an option.
You could use this batch method in conjunction with a CAML query to delete some of the items from a list which you may find some use for?

Aidan

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading