Sunday, March 17, 2013

Get List Items and Folders

When using Object Model API to get list items, the list item collection results could be very different depending on how you use the API.
1. List.Folders
List.Folders will return all sub folders of a list or a folder recursively.
foreach (SPListItem item in currList.Folders)
{

// item are sub folder of list recursively.
if (item.Folder.Exists)
{ ... }
}
2. List.Items will return all items under all sub folders recursively without folder item.
// List.Items get items from all sub folders recursively but it doesn't contain folder item
foreach (SPListItem item in currList.Items)
{
... ...
}
3. User SPQuery to return all items under a specific folder recursively without folder item.
SPQuery query = new SPQuery();
query.Folder = item.Folder; // item is an object of SPFolder
// When recursive is used, it only returns item that is not folder

query.ViewAttributes = "Scope=\"Recursive\"";
SPListItemCollection itemList = currList.GetItems(query);

4. User empty default SPQuery to get items under current root/current folder non-recursively but result includs both items and folders
SPQuery query = new SPQuery();
SPListItemCollection itemList = currList.GetItems(query);
// items contains folder, need to skip folder item
foreach (SPListItem item in itemList)
{
// all items should be type of File except folders
if (item.FileSystemObjectType != SPFileSystemObjectType.File)
{
continue;
}

1 comment: