2 best practices loop in SharePoint list – What is the right way to iterate or loop through List Items? In this article, we will learn what is the right way to iterate or loop through the SharePoint list items either from SharePoint on-premise or SharePoint online – o365.
What is Loop in Programming Languages?
In programming languages, a loop is a control structure that repeatedly executes a block of code as long as a specified condition is true. Loops are fundamental to programming as they enable automation and efficient processing of repetitive tasks.
Types of Loops
- For Loop:
- Usage: Typically used when the number of iterations is known beforehand.
- Structure:
python
for i in range(10):
print(i)
- While Loop:
- Usage: Used when the number of iterations is not known and the loop should continue until a certain condition is met.
- Structure:
python
i = 0
while i < 10:
print(i)
i += 1
- Do-While Loop:
- Usage: Similar to the while loop, but it guarantees that the code block will be executed at least once.
- Structure (Note: Not available in Python, shown here in JavaScript):
javascript
let i = 0;
do {
console.log(i);
i++;
} while (i < 10);
- For-Each Loop:
- Usage: Used to iterate over elements in a collection or array.
- Structure:
python
items = [1, 2, 3, 4, 5]
for item in items:
print(item)
Loop Control Statements
- Break:
- Usage: Exits the loop immediately, regardless of the loop condition.
- Example:
python
for i in range(10):
if i == 5:
break
print(i)
- Continue:
- Usage: Skips the current iteration and proceeds with the next iteration of the loop.
- Example:
python
for i in range(10):
if i == 5:
continue
print(i)
- Pass:
- Usage: Does nothing and acts as a placeholder in a loop or conditional statement.
- Example:
python
for i in range(10):
if i == 5:
pass
print(i)
Nested Loops
- Usage: A loop inside another loop, useful for working with multi-dimensional data structures like matrices.
- Example:
python
for i in range(3):
for j in range(3):
print(f"i={i}, j={j}")
Common Loop Use Cases
- Iterating over a Range:
- Used to perform an action a specific number of times.
pythonfor i in range(5):
print("Hello")
- Processing Items in a Collection:
- Used to perform actions on each item in a list, tuple, or other iterable.
pythonnumbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number * 2)
- Reading Data Until a Condition is Met:
- Often used in data input or file reading scenarios.
pythonuser_input = ""
while user_input != "exit":
user_input = input("Enter a command: ")
print(f"You entered: {user_input}")
Loop Performance and Optimization
- Efficiency: Poorly designed loops can lead to inefficient code and performance bottlenecks, particularly with large datasets.
- Optimization: Use techniques like minimizing the number of operations inside the loop, avoiding unnecessary computations, and using appropriate data structures to enhance performance.
Loops are an essential part of programming, enabling repetitive tasks to be automated efficiently and effectively. Understanding and utilizing different types of loops and control statements can significantly enhance the functionality and performance of your code.
Introduction – Best practices loop in SharePoint list
Generally, when a developer writes the code quickly – this might be observed. Let’s say in SharePoint “PurchaseOrder” list, there are 500 items. And thru the SharePoint object model coding, we want to read these 500 items and display the “OrderNo” column. For this, the code can be written as below:
Sample code(untested):
string strUrl = "server001:1111/"; using(SPSite oSite = new SPSite(strUrl)) { using(SPWeb oWeb = oSite.OpenWeb()) { SPList poList= oWeb.Lists["PurchaseOrder"]; for(int i=0;i<500 && i<poList.Items.Count;i++) //This is an overhead to SQL database. { SPListItem oneListItem = poList.Items[i]; Console.WriteLine(oneListItem ["OrderNo"])+ "\n"); } } }
Analysis of the above code – Best practices looping SharePoint (loop in SharePoint list)
Even though we are iterating 500 times – internally for each iteration it sends requests to the SQL database server twice i.e. one is for poList.Items.Count and another one are for the actual item. So for 500 items internally 1000 times, the above code sends the request to the SQL server which is not recommended, and hits the performance of the code.
What is the recommended way to write the above code? best practices looping SharePoint (loop in SharePoint list)
The above code can be written below way – just instead of passing the items. count inside the loop, we need to assign all 500 items in the SPListItemCollection variable – then this variable can be passed inside the loop. This way we can reduce half of the SQL server trip for the above scenario. On top of these, when the first time – SPListItemCollection gets the 500 items from SQL, it is stored in memory and gets cached, so from the subsequent looping, items are fetched from the cached memory. Hence it speeds up the execution.
Sample code(untested):
string strUrl = "server001:1111/"; using(SPSite oSite = new SPSite(strUrl)) { using(SPWeb oWeb = oSite.OpenWeb()) { SPList poList= oWeb.Lists["PurchaseOrder"]; SPListItemCollection poItems = poList.Items; //This code only one time sends the request to SQL and caches the resulted items in the memory. for(int i=0;i<500 && i<poItems.Count;i++) { SPListItem oneListItem = poItems[i]; Console.WriteLine(oneListItem["OrderNo"])+ "\n"); //The individual item is being read and displayed from the "poItems" variable not directly from SQL. } } }
More optimization on the above code – in fact, the most recommended one: Looping SharePoint best practices
Let’s say we have thousands of items on the list – then if we want to fetch them, we should not fetch all items at a time like above. In this scenario – we should use SPQuery or CAML (Collaborative Markup Language) query.
Sample code(untested):
using(SPSite oSite = new SPSite(strUrl))
{
using(SPWeb oWeb = oSite.OpenWeb())
{
SPList poList= oWeb.Lists[“PurchaseOrder”];
SPQuery query = new SPQuery();
query.RowLimit = 300; // As an example retrieve 300 items.
query.ViewFields = “OrderNo’/>”; //We can use the view fields attributes of SPQuery,when we want to retrieve the specific column from database.
SPListItemCollection poItems = poList.GetItems(query);
for(int i=0;i<500 && i<poItems.Count;i++)
{
SPListItem oneListItem = poItems[i];
Console.WriteLine(oneListItem[“OrderNo”])+ “\n”);
}
}
}
Summary: Looping SharePoint best practices (loop in SharePoint list)
Thus, in this article, we have learned that how the recommended way we can query the list item data in SharePoint.
See Also: SharePoint Online tutorial (loop in SharePoint list)
You may also like the below SharePoint Online tutorials:
- Office 365: Getting started with SharePoint PnP PowerShell – installation
- In 2 steps convert a classic SharePoint page to modern using PnP
- Office 365: Retrieve hub sites and associated sites using PnP Powershell
- Create a modern team site using PnP PowerShell in SharePoint
- In 4 steps access SharePoint online data using postman tool
- SharePoint admin center: Learn SharePoint online administration in an hour – step by step
- SharePoint REST API: GET vs POST vs PUT vs DELETE vs PATCH
- Office 365: Understanding the hub site in SharePoint online
- Programming models in SharePoint