Welcome to my blog, stay tunned :
Home | Blogs | Stephane Eyskens's blog

Leveraging .NET 4 in SharePoint 2013 Series (3) - SortedSet

Hi,

I'll be writing a series of blog posts about leveraging .NET 4 within SharePoint 2013. As you might know already, SharePoint 2013 is now based on this .NET runtime version v4.0.30319 which actually allows developers to benefit from .NET 4 features. You couldn't do that with SharePoint 2010 which was still based on .NET runtime v2.0.50727.

SortedSet

SortedSet is a new collection allowing you to optimize sorting. Let's take a basic example of it. Say you want to sort lists of a given SharePoint site alphabetically. Up to now, you would have done probably like this:

var SortedLists = Web.Lists.Cast<SPList>().OrderBy(l => l.Title);
foreach (var SortedList in SortedLists)
{
  //do something    
}

With the SortedSet, you can do this way :

public class ListByTitle : IComparer<SPList>
{
    CaseInsensitiveComparer Comp = new CaseInsensitiveComparer();

    int IComparer<SPList>.Compare(SPList l1, SPList l2)
    {
        return Comp.Compare(l1.Title, l2.Title);           

    }
}

You prepare the comparison logic and then, you build the SortedSet like this:

SortedSet<SPList> Lists = new SortedSet<SPList>(new ListByTitle());
foreach (SPList l in Web.Lists)
    Lists.Add(l);
                    
foreach (SPList l in Lists)
{
  //do something                        
}

While the LINQ patterns is more appealing and easier to use, the performance difference is quite impressive. With only 40 items, the SortedList approach was 10 times faster on all my tests.

Happy Coding!