11

I am new to SharePoint and want to delete all rows in a SharePoint list using C# ClientContext class and CAML Query.

How can i achieve it efficiently?

Mahmoud Farahat
  • 5,364
  • 4
  • 43
  • 59
Yogesh
  • 3,394
  • 9
  • 31
  • 46

2 Answers2

17

I solved it. The learning was that we need to delete the items of list in reverse order.

Link: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitemcollection.delete.aspx

ListItemCollection listItems = oList.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(listItems,
                    eachItem => eachItem.Include(
                    item => item,
                    item => item["ID"]));
clientContext.ExecuteQuery();

var totalListItems = listItems.Count;
Console.WriteLine("Deletion in " + currentListName + "list:");
if (totalListItems > 0)
{
    for (var counter = totalListItems - 1; counter > -1; counter--)
    {
        listItems[counter].DeleteObject();
        clientContext.ExecuteQuery();
        Console.WriteLine("Row: " + counter + " Item Deleted");
    }
}
Thor
  • 498
  • 1
  • 6
  • 15
Yogesh
  • 3,394
  • 9
  • 31
  • 46
  • 8
    As far as efficiency goes you would probably be well served to move the ExecuteQuery() statement outside of the loop. – Lee Richardson May 29 '13 at 20:53
  • 4
    If you move the ExecuteQuery to the outside of the loop, and you have many deletes sent as 'one execution' you could potentially run into an exception where Sharepoint thinks your request is too big (it happened to me with a couple thousand deletes). See http://sharepoint.stackexchange.com/questions/44894/client-object-model-microsoft-sharepoint-client-serverexception-the-request – n00b Mar 22 '16 at 02:20
  • 6
    i Agree with @n00b but in order to reduce network overhead I'd add `if (counter % 100 == 0){ clientContext.ExecuteQuery(); }` – Emaborsa Jun 07 '16 at 09:42
0

Another workaround: - Create a items (said: deleteAllItems), on a new list (said: configuration).

  • Use CAML to change that deleteAllItems value from False to True.

  • then, use workflow,

    if deleteAllItems == True, delete all items.

    reset deleteAllItems to False.

Solve the client side performance issue. :)

YHTAN
  • 626
  • 5
  • 19