Dienstag, 22. Mai 2012

Delete items from a SPListItemCollection

Just a really dumb error I made when deleting items from a SPListItemCollection. This is my code:

SPListItemCollection listCollection = list.GetItems(spQuery);
for (int i = 0; i < listCollection.Count; i++)
{
listCollection.Delete(i); //listCollection.Delete(0)
}


What I did before was to go through the Count() method of the list-item-collection. This is wrong, because the amount of Count() changes during this operation. That means, not everything will be deleted. Use the code bellow. It will loop really through each item and will delete the dynamically changed first item of the list-collection.

SPListItemCollection listCollection = list.GetItems(spQuery);
int counter = listCollection.Count;
for (int i = 0; i < counter; i++)
{
listCollection.Delete(0);
}


That means you should be aware, that the index and the Count() method change, when performing a Delete() operation.