Posted by: R Manimaran | December 10, 2010

Lambda Expressions in SharePoint

In the Previous article we have seen how to use Lambda expression. Here we will have some Lambda expressions in SharePoint.

Using Lambda expressions in SharePoint

public static void EnumerateAllCustomList()

{

using (SPSite oSPSite = new SPSite(“http://servername”))

{

using (SPWeb oSPWeb = oSPSite.OpenWeb())

{

var lists = oSPWeb.Lists.OfType<SPList>().Where

(

l => l.BaseTemplate == SPListTemplateType.GenericList

);

foreach (SPList list in lists)

{

Console.WriteLine(list.Title);

}

}

}

}

Filter the ListItems

public static void FilterListItems()

{

using (SPSite oSPSite = new SPSite(“http://servername”))

{

using (SPWeb oSPWeb = oSPSite.OpenWeb())

{

SPList oList = oSPWeb.Lists.GetListByListName(“Demo”);

var items = oList.Items.OfType<SPListItem>().Where

(

l => l.ID > 2

);

foreach (SPListItem item in items)

{

Console.WriteLine(item.Title);

}

}

}

}

Using Multiple Where Clause condition in Lambda Expression

public static void FilterListItemsWithAnd()

{

using (SPSite oSPSite = new SPSite(“http://servername”))

{

using (SPWeb oSPWeb = oSPSite.OpenWeb())

{

SPList oList = oSPWeb.Lists.GetListByListName(“Demo”);

var items = oList.Items.OfType<SPListItem>().Where

(

l => l.ID > 2 &&

Convert.ToInt32(l[“Experience”]) >= 7

);

foreach (SPListItem item in items)

{

Console.WriteLine(item.Title);

}

}

}

}

Ordering the Filter Items

Add the line above the foreach Statement.

//Order By Ascending Based on Title

items = items.OrderBy(i => i.Title);

//Order By Descending Based on Title

items = items.OrderByDescending(i => i.Title);

The above OrderBy can be combined in one statement as below.

var items = oList.Items.OfType<SPListItem>().Where

(

l => l.ID > 2 &&

Convert.ToInt32(l[“Experience”]) >= 7

).OrderBy(l=>l.Title);

OrderBy Multiple Columns

var items = oList.Items.OfType<SPListItem>().Where

(

l => l.ID > 2 &&

Convert.ToInt32(l[“Experience”]) >= 7

)

.OrderBy(l=>l[“Experience”])

.ThenBy(l=>l.Title);

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: