I got to delete the list items from a list. This sounds to be an easy task i.e. loop through the list item collection and delete the items. That would be the intuitive way, but then again this is the SharePoint Object Model. Lets see what would be the way to delete items.

The INTUITIVE way:

     SPList spList = oWeb.Lists.TryGetList("My List");
     SPQuery query = new SPQuery();
     query.Query = string.Format("<Where><Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq></Where>", "Title", "SharePoint" );

     SPListItemCollection listItemColln = spList.GetItems(query);

     foreach (SPListItem item in listItemColln)
     {
       item.Delete();
     }

But when you execute the about code, you will go into an error i.e.

 Collection was modified; enumeration operation may not execute.

So to delete a list items from an SPListItemCollection object we need to follow another approach i.e.

SPList spList = oWeb.Lists.TryGetList("My List");
SPQuery query = new SPQuery(); 
query.Query = string.Format("<Where><Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq></Where>", "Title", "SharePoint"; 
SPListItemCollection listItemColln = spList.GetItems(query); 
int itemCount = listItemColln.Count; 
for (int i=0;i < itemCount;i++) 
{ 
listItemColln.Delete(0); 
}

And here you go. This way all the items are deleted from the list item collection. Happy Coding… 🙂

Advertisements