Tuesday, 19 January 2016

How to retrieve all items from list (having more than 5000) using CSOM?

Hi All,


As we know that by default the Threshold limit to retrieve litem from a list is 5,000 and OneDrive for Business has a 20,000 limit.
So any list with more then 5,000 items can cause some problems in your apps.


Luckily CSOM allows you to retrieve all items by using the ListItemCollectionPostion. Every time you execute a query for list items, you will be presented with a ListItemCollection that contains the ListItemCollectionPosition.


If that ListItemCollectionPosition is not null you can use that position to execute the same query again, however with a different starting point. This way you can ‘loop’ through all items in a list and construct an object that contains all your items. By putting everything in a while loop you are making sure that you will retrieve all items.



string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
Web site = clientContext.Web;
List targetList = site.Lists.GetByTitle("Announcements");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><ViewFields><FieldRef Name='Title'/></ViewFields><RowLimit>10 </RowLimit></View>";
ListItemCollection collListItem = targetList.GetItems(query);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
string msg = "Titles, 10 at a time:\n";
foreach (ListItem myListItem in collListItem)
msg += "\nTitle=" + myListItem["Title"];
Console.WriteLine(msg);
ListItemCollectionPosition position = collListItem.ListItemCollectionPosition;
do
{
msg = "";
query.ListItemCollectionPosition = position;
collListItem = targetList.GetItems(query);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
position = collListItem.ListItemCollectionPosition;
foreach (ListItem myListItem in collListItem)
msg += "\nTitle=" + myListItem["Title"];
Console.WriteLine(msg);
} while (position != null);




No comments:

Post a Comment