Lambda expressions SharePoint 2013

Lambda expressions SharePoint 2013:-

A lambda expressions is an anonymous function that you can use to create delegates or expression tree types.

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().Where
(
li => li.BaseTemplate == SPListTemplateType.GenericList
);
foreach (SPList list in lists)
{
Console.WriteLine(list.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().Where
(
li => li.ID > 2 &&
Convert.ToInt32(li[“Experience”]) >= 7
);
foreach (SPListItem item in items)
{
Console.WriteLine(item.Title);
}
}
}
}[AdSense-A]

Filter the ListItems

public static void FilterListItems()
{
using (SPSite oSPSite = new SPSite(“http://servername”))
{
using (SPWeb oSPWeb = oSPSite.OpenWeb())
{
SPList oList = oSPWeb.Lists.GetListByListName(“ListName”);
var items = oList.Items.OfType().Where
(
l => l.ID > 2
);
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().Where
(
l => l.ID > 2 &&
Convert.ToInt32(l[“Experience”]) >= 7
).OrderBy(l=>l.Title);
OrderBy Multiple Columns
var items = oList.Items.OfType().Where
(
l => l.ID > 2 &&
Convert.ToInt32(l[“Experience”]) >= 7
)
.OrderBy(l=>l[“Experience”])
.ThenBy(l=>l.Title);