15 June 2010

Lambda Expressions

Well, Lets go back to my previous code samples. click here. There we have used one expression something like this.
 Customer  customer = db.Customers.Single(c=> c.Name == "Mark Walker");
Lets take the expression out.So this will looks:
(Input parameters) => Expression
This is nothing but Lambda Expression. If you have been reading about LINQ and its related technologies at all, you’ve surely come across this term already. Lambda expressions are one of the features introduced in the C# 3.0.A lambda expression is an anonymous function that can contain expressions and statements, and can be  used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.Ok, if this complicates you lets take a small example. Let’s go back to the customer collection and query it.
var cust = new List<customer> {
new customer { Name="Bob"}
, new customer { Name="Sally" }
, new customer { Name="Jack"}
, new customer { Name="Sarah"}
, new customer { Name="Philbert"}           
};
string strResult = customer.Find(IsCustomer);
public static bool IsCustomer(string name)
{
   return name.Equals("Ken");
}
We can write the same thing in Anonymous method. The idea behind writing the anonymous methods is to write methods inline to the code without declaring a formal named method. Normally they used for small methods that don't require any reuse. So this will looks something like this.
string strResult = customer.Find(delegate(string cust)
{
   return cust.Equals("Ken");
});
Lambda Expressions makes the thing even more easier by allowing you to write avoid anonymous method and statement block So we can say it as something like modified version of Anonymous method from C# 2.0.
var customeres = cust.Where((c) => c.Name == "Ken").Select((c) => new { c.Name });
This is very common way of witting code, and if any plan to work with LINQ soon you will come across this. The biggest thing is that treating the code as data.

No comments: