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
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
(); 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
().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.