Introduction to SharePoint Queries
Recently I’ve been using SharePoint Queries more and more, not to say in my latest personal project: Zimmergren Forum WebPart. At times when I’ve been out at some clients to help them either refactor existing code or build new code, weather doing it myself of joining an existing SharePoint team – I always bump into things that could be solved using Queries instead of the way they’ve solved it using for- and foreach loops to go through entire lists with if-statements checking if that’s what they’re looking for.
Example: Code not using queries.
The following few lines of code is a sample of how you could fetch some SPListItems and check weather they’re what you’re looking for or not – without using SharePoint Queries (SPQuery). I’ve seen this kind of implementation one time too many and thought that it’d try to clarify the benefits with using SharePoint Queries.
Sample code without queries:
int counter = 0;
SPList myList = SPContext.Current.Web.Lists["ForumList"];
foreach (SPListItem forumItem in myList.Items)
{
if (forumItem["ForumID"].ToString() == forumID.ToString())
counter++;
}
return counter;
This code will work well if you don’t have too many items in your list. But if you’d have a couple of hundred or even thousand items in the list, it’d take way too long to loop through each of these items to see if the ForumID matches the item’s forumID.
Example: Code using queries
To solve this issue, you should instead make use of the SPQuery (Microsoft.SharePoint.SPQuery) object in order to retreive only the items that actually contains the ForumID that you’re looking for – without the need for checking each and every item in the list. This will increase performance drastically if you’ve got a couple of thousand items in a list and making a lot of calls to the method that gathers list items.
Sample code that makes use of SharePoint Queries (SPQuery)
SPList myList = SPContext.Current.Web.Lists["ForumList"];
SPQuery query = new SPQuery();
query.Query = string.Format("<Where><Eq><FieldRef Name=\"ForumID\" /><Value Type=\"Number\">{0}<\Value></Eq></Where>", forumID); //forumID comes as a parameter to the method being called
SPListItemCollection listItems = myList.GetItems(query);
return listItems.Count;
The code above will significantly increase performance of your code if there’s plenty of items in the list.
Conclusion
This post was not meant to teach the technique of using SharePoint queries, but rather to enlighten you on the fact that there’s a performance boost if you learn to use SPQuery instead of a bunch of if-statements to get specific ListItems.
I’ll cover the basics and more all-around techniques of using Queries in my next blogpost!