Sorting SharePoint 2010 SPFolders and SPFiles

Sometimes you want to iterate through all SPFolders in a list or library, or all items in a list or folder. You may have noticed that the folders or items seem to come back in no particular order. You probably want to sort them in some order…

The best I got from Google was this post, but I think it can be done even sleeker. First create a temporary generic list, then sort it using a neat Lambda expression, and finally iterate over the temporary list:

// folder is some SPFolder, e.g. SPList.RootFolder
List<SPFolder> spFolders = folder.SubFolders.Cast<SPFolder>().ToList();
spFolders.Sort((f1, f2) => f1.Name.CompareTo(f2.Name));

foreach (SPFolder subFolder in spFolders)
	// Your code here

Same procedure for SPFiles

// folder is some SPFolder, e.g. SPList.RootFolder
List<SPFile> spFiles = folder.Files.Cast<SPFile>().ToList();
spFiles.Sort((f1, f2) => f1.Name.CompareTo(f2.Name));

foreach (SPFile file in spFiles)
	// Your code here

I assume this work because the SPFolder.Files and SPFolder.SubFolders properties both are of a type that inherit the SPBaseCollection class. Thus, you should be able to use this method on any type that inherits one of the classes listed in SPBaseCollection’s inheritance hierarchy. For instance, SPSite.AllWebs, SPList.Items and SPList.Fields should all be sortable as shown above

Of course, while I sort alphabetically using the Name property in this example, you can sort on any property you want, like the TimeLastModified.

As always: Comments, questions, likes, dislikes, etc. are welcome!


About Øystein Garnes

Software Project Manager, former .Net and SharePoint 2010 developer, husband, Boston Terrier owner, amateur caveman chef, amateur genealogist, cross country skier, food blogger.
This entry was posted in SharePoint and tagged , . Bookmark the permalink.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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