Tuesday 10 March 2015

Deleting List Items in Bulk in SharePoint 2010

There are times when we have a list of records to be deleted from a SharePoint list and we do not want to loop it one by one and delete it for performance reason. There is a better way to deal with these type of scenario.

The method which is used for this is ProcessBatchData.

See the below code snippet how to use this.


SPSite _site = SPContext.Current.Site;
SPWeb _web = _site.OpenWeb();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    SPList _list = _web.Lists["ListName"];

    SPQuery _query = new SPQuery();
    _query.Query = "<Where><Eq><FieldRef Name='PrimaryKeyID' /><Value Type='Text'>"PrimaryKeyID + "</Value></Eq></Where>";
    SPListItemCollection _collection = _list.GetItems(_query);
    if (_collection.Count > 0)
      {
         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 _collection)
          {
            sbDelete.Append(string.Format(command, item.ID.ToString()));
          }
          sbDelete.Append("</Batch>");
          _web.ProcessBatchData(sbDelete.ToString());
      }
});