Martin Bodocky

No less, no more. Just live between code.

SPQuery Get all items from SharePoint list


Recently I was
really surprised when I forgot add to my SPQuery a scope, therefore I created this article about. Next reason why was my google searching which shows me that more people don’t using scope for searching and they can be really bad
surprised when their queries don’t match their expectations.

 

For now I show you all scopes which you can use for query:

Member name

Description

Default

Show only the files and subfolders of a specific folder.

Recursive

Show all files of all folders.

RecursiveAll

Show all files and all subfolders of all folders.

FilesOnly

Show only the files of a specific folder.

 

Informationposted here <http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spviewscope.aspx>

 

In my case I will compare results of queries above my SharePoint list which contains 561 items stored in folders and subfolders.

 

Here is a source code of comparison:

 

string siteUrl = @”http://xxxxxxx&#8221;;

using (SPSite site = new SPSite(siteUrl))

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Project Documents"];

     Console.WriteLine(“List: “ + list.Title);

     Console.WriteLine(“ReallyCount: “ + list.ItemCount);

     //First attempting with empty query return only first line of items

     SPQuery spQry = new SPQuery();

     spQry.RowLimit = 300;

     do

     {

           SPListItemCollection items = list.GetItems(spQry);

           Console.WriteLine(“FirstQuery: “ + items.Count);

           spQry.ListItemCollectionPosition = items.ListItemCollectionPosition;

} while (spQry.ListItemCollectionPosition != null);

//First attempting with empty query return all lines of items because you set recursive scope

     spQry = new SPQuery();

     spQry.ViewAttributes = “Scope=\”RecursiveAll\”";

     spQry.RowLimit = 300;

     do

     {

           SPListItemCollection items = list.GetItems(spQry);

           Console.WriteLine(“SecondQuery: “ + items.Count);

           spQry.ListItemCollectionPosition = items.ListItemCollectionPosition;

} while (spQry.ListItemCollectionPosition != null);

}

Console.Read();

 

Outcome:

 

How you can see in
first attempting was failed because in first line in my library is only 8
folders what cannot match with all 561 items, but in my second attempting is
result better so expected 561 items dedicated with two outs according to best
practise how to working with bigger lists.

 

Happy coding guys :)

 

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: