Programatically delete All items from a List

I had to delete and re-populate items in a SharePoint List (more than 4000 items!) using a Web Part. Initially I tried by enumerating the list items and deleting them one by one. But it was taking a long time to delete the list items and re-populate the list with information collected from various sub-sites by crawling throught them. After some googling I fould another way of deleting the List items in bulk using CAML query. The code is give below. I noticed a significant difference in time taken for deleting the list items between using deleting items one by one and deleting the items in bulk using CAML.

Code starts —–>

////Delete the existing entries from list using CAML query
System.Text.StringBuilder sbDelete = new System.Text.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, Convert.ToString(item.ID)));

<——- Code ends

I found this information from the blog Mwalimu’s Corner.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s