Correct way to delete all SPListItems

SharePoint 2016 Logo

Today while coding a Sharepoint timer job I needed to clean my SPList.

I tried common ways of deleting using “foreach” and “for i++ …” but I got the error. I couldn’t delete list and create it again in timer job because of custom views. As usually for SharePoint solution is not ordinary 🙂

So, as it turned out, correct syntax of deleting all SPListItems is using “for i–“:

for (int i = list.Items.Count - 1; i >= 0; i--) { 
    list.Items.Delete(i); 
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *