Howto: Use lambda expression in SharePoint Object model

English

Lambda expression has been introduced since .NET framework 3.5, it is an anonymous function that can contain statement and expression. For more understanding on lambda expression you can read directly in MSDN page here. I will assume that you have read the topic and you can remember the lambda simply as:

(input parameters ) => operation

We will start with very basic operation of using lambda expression in SOM, and I hope you’ll find your path for more complex one. (note some code may not be efficient, for the clarity purpose)

A.  Start with OfType<TResult>() function to get IEnumerable that implement query pattern.

Example:

Originally to browse to all Site collection in WebApplication we will write,

SPWebApplication webApplication = SPContext.Current.Site.WebApplication;

SPSiteCollection allSPSite = webApplication.Sites;

foreach(SPSite spSite in allSPSite)

{

      // operation in the SPSite

}

the equivalent for our lambda starter is,

SPWebApplication webApplication = SPContext.Current.Site.WebApplication;

var allSPSite = webApplication.Sites.OfType<SPSite>();

foreach(SPSite spSite in allSPSite)

{

      // operation in the SPSite

}

B. Use lambda expression in the IEnumerable

Example :

You need to list all Site collection which uses STS site template.

Originally you will write,

SPWebApplication webApplication = SPContext.Current.Site.WebApplication;

SPSiteCollection allSPSite = webApplication.Sites;

foreach(SPSite spSite in allSPSite)

{

      if(spSite.RootWeb.WebTemplate.Equals(“STS”,StringComparison.InvariantCultureIgnoreCase))

     {

           // Do operation in selected site

     }

}

the equivalent using lambda is,

SPWebApplication webApplication = SPContext.Current.Site.WebApplication;

var allSPSite = webApplication.Sites.OfType<SPSite>().Where(s => s.RootWeb.WebTemplate.Equals("STS", StringComparison.InvariantCultureIgnoreCase));

foreach(SPSite spSite in allSPSite)

{

      // operation in the SPSite

}

Ok, now I believe you will get the idea of how to use lambda expression in SOM collection. In next posting, I’ll cover directly to the sample usage of the lambda.

2 thoughts on “Howto: Use lambda expression in SharePoint Object model

  1. Pingback: Howto series : Lambda and SharePoint « Ideas for free

  2. Hey ,

    Nice article !! .

    I am trying to write a lambda expression which can fetch all lists that are based on a particular content Type . as content type collection is an IEnumerable , not sure how to form the query . Please let me know if there is a solution to this problem.

    Thanks so much for your time

Leave a Reply