If you’ve ever used the SPQuery objects to get SPListItems from a SPList, and you didn’t get it to work because the query would return ALL items in the SPList, you might have used code similar to this:
SPQuery postsQuery = new SPQuery();
postsQuery.Query = string.Format("<Where><Eq><FieldRef Name='ThreadId' /><Value Type='Text'>{0}</Value></Eq></Where>", threadID);
SPList allPosts = SpecificForumData.GetPostList(); // Custom method to get the SPList object
SPListItemCollection posts = allPosts.GetItems(postsQuery);
I’ve always built my queries by hand (what better way to learn than trial and error, right?), but when I tried the U2U CAML Query Builder to construct my SPQuery it suddenly all failed, and all items in the SPList was returned.
To solve this issue, just remove the and tags from the generated query that U2U CAML Query Builder produces and it should all work again.
So, replace the above code with this:
SPQuery postsQuery = new SPQuery();
postsQuery.Query = string.Format("<removed in blog migration>", threadID);
SPList allPosts = SpecificForumData.GetPostList(); // Custom method to get the SPList object
SPListItemCollection posts = allPosts.GetItems(postsQuery);
If all is well, you should now be able to run this query to get better performance AND return only the selected SPListItem objects from the SPList
Hope it helps someone :)
Comments are closed
Archived comments
Speaking about whats faster, between looping the list and using SPQuery, I see here that you in your loop you are using tostring() function. This function will take more time than using something like string.concat() or string.format(). So, will SPQuery be still be faster if the latter string conversion functions are used "
Hi Sameer,
Thank you for the comment.
As for the actual SPQuery itself, it doesn't really matter how you construct the string as long as it's constructed as an accurate query. As for .NET performance however, it may differ in some scenarios but I don't think it would make any difference right here.
Performance should always be kept in mind in the code, so good thinking :-)