In the below code snippet we are going to Delete multiple list items (which returned from a CAML query) from a sharepoint list using
Object modeling.
Assumptions::
listItemFieldID --> List item ID internal field
listItemFieldName --> List item field which you will be querying.
listItemName --> value of the field
Code::
SPSite ospSite = null;
SPWeb ospWeb = null;
SPList ospList = null;
SPListItemCollection spListItems = null;
string camlViewQuery = string.Empty,
camlFilterQuery = string.Empty,
listItemFieldID = "ID";
//view fields query depends on your requirement
camlViewQuery = "<FieldRef Name='"
+ listItemFieldID + "' /><FieldRef
Name='" + listItemFieldName + "'
/>";
//filter query depends on your requirement
camlFilterQuery = "<Where><Eq><FieldRef
Name='" + listItemFieldName + "'/><Value
Type='Lookup'>" + listItemName + "</Value></Eq></Where>";
using (ospSite = new
SPSite(siteUrl))
{
using (ospWeb = ospSite.OpenWeb())
{
try
{
ospWeb.AllowUnsafeUpdates = true;
ospList = ospWeb.Lists.TryGetList(listName);
if (ospList != null
&& ospList.ItemCount > 0)
{
SPQuery query = new
SPQuery()
{
//query the list.
Query = camlFilterQuery,
ViewFields = camlViewQuery,
ViewFieldsOnly = true,
};
spListItems = ospList.GetItems(query);
if (spListItems!= null)
{
foreach (SPListItem
listItem in spListItems)
{
ospList.Items.GetItemById(Convert.ToInt32(listItem["ID"])).Delete();
}
}
ospList.Update();
ospWeb.Update();
ospWeb.AllowUnsafeUpdates = false;
}
}
catch (Exception
ex)
{
}
}
}
Hope this helps..