Sharepoint - Fastest way to delete all items with C#

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;
}

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(); 
}

Tags: