Friday, December 28, 2012

SharePoint Object model code to delete items from large lists

Scenario: You have thousands of items in a SharePoint list and you want to delete them, in a way that query should not take longer to execute.

1. Construct a CAML query for each item in a list you want to delete
2.  You can then pass on the aggregated CAML query for all the items to OOB ProcessBatchData() function as below:-
private static StringBuilder BuildBatchDeleteCommand(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())); 

 return sbDelete;

  string strBatchDelete = BuildBatchDeleteCommand(list).ToString();
string strProcessBatch = site.RootWeb.ProcessBatchData(strBatchDelete);

This will place the items in a recycle bin. So to delete items from the recycle bin use

 Refer to below form post to do it using powershell:-