21

Possible Duplicate:
Deleting all the items from a large list in SharePoint

What is the fastest way to delete all items in a list programmatically? I do not want to remove list and re-create it, but I need to get rid of all items.

The way I do it right now, with a console application:

SPList list = mWeb.GetList(strUrl);
if (list != null)
{
    for (int i = list.ItemCount - 1; i >= 0; i--)
    {
        list.Items[i].Delete();
    }
    list.Update();
}
Tschareck
  • 2,155
  • 7
  • 35
  • 52

3 Answers3

28

Fastest way to delete all items is to batch together all delete commands...

public static void DeleteAllItems(string site, string list)
{
    using (SPSite spSite = new SPSite(site))
    {
        using (SPWeb spWeb = spSite.OpenWeb())
        {
            StringBuilder deletebuilder = BatchCommand(spWeb.Lists[list]);
            spSite.RootWeb.ProcessBatchData(deletebuilder.ToString());
        }
    }
}

private static StringBuilder BatchCommand(SPList spList)
{
    StringBuilder deletebuilder= new StringBuilder();
    deletebuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
    string command = "<Method><SetList Scope=\"Request\">" + spList.ID +
        "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"owsfileref\">{1}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";

    foreach (SPListItem item in spList.Items)
    {
        deletebuilder.Append(string.Format(command, item.ID.ToString(),item["FileRef"].ToString()));
    }
    deletebuilder.Append("</Batch>");
    return deletebuilder;
}
coc2coc
  • 88
  • 5
Falak Mahmood
  • 17,298
  • 2
  • 40
  • 67
  • 2
    depending on the number of the item, you should consider splitting the batch commands in chunks. this will avoid to have a huge xml command to execute (I would fix the batch size to 1000) – Steve B Jun 27 '12 at 07:59
  • I agree and batch size could be fixed to 1000 especially if list contains more than 1000 item. Performance for deleting items degrades significantly when a list becomes very large – Falak Mahmood Jun 27 '12 at 08:20
4

Depends on whether you mean fastest to execute or fastest to code and get working.

As mentioned the batch method will execute fastest, otherwise to do it the way you were doing then this would be quicker:

while(list.Items.Count > 0) 
{ 
  list.Items[0].Delete(); 
}
Ronak Patel
  • 3,261
  • 3
  • 23
  • 45
PlanetWilson
  • 981
  • 5
  • 8
0

The SPWeb.ProcessBatchData is what you are looking for.

Have a look here regarding how to delete items with it: http://coffeeandsharepoint.blogspot.in/2012/04/deleting-items-on-list-using.html

Vardhaman Deshpande
  • 10,462
  • 1
  • 26
  • 52