Skip to content

Instantly share code, notes, and snippets.

@andyhuey
Created December 21, 2016 20:39
Show Gist options
  • Save andyhuey/de2bde00e398e8925a3770e9950c8f48 to your computer and use it in GitHub Desktop.
Save andyhuey/de2bde00e398e8925a3770e9950c8f48 to your computer and use it in GitHub Desktop.
CSOM code to delete all items from a SharePoint list
private void deleteAllFromList(ClientContext cc, List myList)
{
int queryLimit = 4000;
int batchLimit = 100;
bool moreItems = true;
string viewXml = string.Format(@"
<View>
<Query><Where></Where></Query>
<ViewFields>
<FieldRef Name='ID' />
</ViewFields>
<RowLimit>{0}</RowLimit>
</View>", queryLimit);
var camlQuery = new CamlQuery();
camlQuery.ViewXml = viewXml;
while (moreItems)
{
ListItemCollection listItems = myList.GetItems(camlQuery); // CamlQuery.CreateAllItemsQuery());
cc.Load(listItems,
eachItem => eachItem.Include(
item => item,
item => item["ID"]));
cc.ExecuteQuery();
var totalListItems = listItems.Count;
if (totalListItems > 0)
{
Console.WriteLine("Deleting {0} items from {1}...", totalListItems, myList.Title);
for (var i = totalListItems - 1; i > -1; i--)
{
listItems[i].DeleteObject();
if (i % batchLimit == 0)
cc.ExecuteQuery();
}
cc.ExecuteQuery();
}
else
{
moreItems = false;
}
}
Console.WriteLine("Deletion complete.");
}
@ravishankar1730
Copy link

Thanks you @andyhuey

@eugeniojefferson
Copy link

eugeniojefferson commented May 8, 2019

Saved my day!

@blitzmax01
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment