foreach (SPListItem item in list.Items)
{
item.Delete();
}
However theIEnumerator interface does not like deleting things while iterating through them because the list count will change while you're doing it. This is mighty confusing for an iterating loop so that's handled as an error and SharePoint sez, no can do, sorry. I tried using list.Items[0].Delete() as I thought that might work since there will always be at least one item in the collection, but no - when it got to the end of the collection it threw an error and all my old VB programming days of On Error Resume Next could not help me in my attempts to keep the code running after the error.
But anyway. All this has happily become a moot point since discovering the SPWeb.ProcessBatchData() command, since all I have to do is loop through every list in the web and issue a delete command. At first I got to the Microsoft help for this (always, always a bad idea. Sorry, Microsoft, but there it is) and got scared off by talk of OWS files and piles of XML. How and ever, after a bit of digging I found a great entry on Stack Overflow that assures me one does not need to be rooting around obscure XML files in the Twelve Hive in ungraceful fashion, but can build the XML on the fly as a string, feed it in to the ProcessBatchData command and hey presto, you're off:
foreach (SPList list in web.Lists)
{
try
{
//decrement loop so as not to confuse the iEnumerator interface
Console.WriteLine("Deleting list items in following list : " + list.Title);
SPListItemCollection splic = list.Items;
StringBuilder batchString = new StringBuilder();
batchString.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
foreach (SPListItem item in splic)
{
batchString.Append("<Method>");
batchString.Append("<SetList Scope=\"Request\">" + Convert.ToString(item.ParentList.ID) + "</SetList>");
batchString.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");
batchString.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
batchString.Append("</Method>");
}
batchString.Append("</Batch>");
web.ProcessBatchData(batchString.ToString());
}
catch { //whatever }
}
Please note that I actually found this code somewhere on Stack Overflow, but have gone and lost the link. So Unknown Programmer, you have my greatest gratitude for this!
I believe there are Copy and Insert methods also but will have to check those out. I may have a requirement for these, due to SharePoint UI inflexibility, so stay tuned...