Correct way to delete all SPListItems




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

 




3 Comments »

  1. […] Using C# deleting like this – it must be from last to first element (Correct way to delete all SPListItems) […]

    Pingback by Delete all items in SharePoint List using PowerShell « MarkiMarta.com — February 12, 2014 @ 8:39 am

  2. […] I wrote about how to remove SPListItems (correct-way-to-delete-all-splistitems). That solution was for C#, but for PowerShell it’s the same. Now I found some faster way to […]

    Pingback by Truncate SharePoint List using PowerShell. Method 2, faster « MarkiMarta.com — May 22, 2014 @ 6:58 pm

  3. The best practice is do not call SPList.Items.Count. Use SPList.ItemCount instead.

    Comment by Carlos Sosa — July 8, 2014 @ 10:36 am

RSS feed for comments on this post. TrackBack URL

Leave a comment





MarkiMarta.com. Notes of web-specialist
Since 2009
18+