4

I have an issue around using SPListItem.Delete. I am fetching some list items (less than 20) and looping through them using a for loop. In each iteration of the loop, I retrieve a SPListItem using SPListItemCollection.GetItemByID method. And then I execute a Delete(). However, it only deletes half the items.

Can some one please help?

Code follows:

 SPListItemCollection listItems = Get_Items();
                 for (int i=0; i<listItems.Count; i++)

            {
                SPListItem currentListItem = listItems.GetItemById(listItems[i].ID);

                currentListItem.Delete();

            }

Thanks,

1 Answers1

4

Try to start from i=listItems.Count-1 to avoid looping on items that already deleted!

for(int i=listItems.Count-1 ; i >= 0 ; i--)
    {
          SPListItem currentListItem = ListName.Items[i];
          currentListItem .Delete();
     }

or

for(int i=listItems.Count-1 ; i >= 0 ; i--)
    {
          SPListItem currentListItem = listItems.GetItemById(listItems[i].ID);
          currentListItem .Delete();
     }
Mohamed El-Qassas MVP
  • 45,382
  • 9
  • 53
  • 96