25/5/09

Deleting multiple items from a list

When we try to delete multiple items from a list we'll have this error:

Collection was modified; enumeration operation may not execute.

The problem is because we are updating the item collection. The solution is to use a decrementing 'FOR' loop. Before use it, I filter the items with a SPQuery to finish the FOR loop quickly.

Here is my example:

SPList recursos = properties.OpenWeb().Lists["Recursos"];
SPQuery query = new SPQuery();


string filtro = "";
filtro += "";
filtro += "";
filtro += "";
filtro += properties.ListItemId.ToString();
filtro += "";
filtro += "";

if (!string.IsNullOrEmpty(filtro))
{
query.Query += "";
query.Query += filtro;
query.Query += "";
}

SPListItemCollection coleccion = recursos.GetItems(query);

try
{
for (int i = coleccion.Count - 1; i >= 0; i--)
{
coleccion[i].Delete();
}
}
catch(Exception ex)
{
SPUtility.SendEmail(web, false, false, {email}, ex.Message);
}