Thursday, February 12, 2009

.Net Lambda Expression

I’ll be as short and practical as possible,

So, if in one Sentence I have to explain Lambda Expression, it’s like

“Lambda Expression is short form of Anonymous delegate”

How to explain this Sentence? Best way is to explain the Evolution of Lambda Expression by an example.

Ok, suppose we have List of names and we want to find the name that starts with “A”,

1) Suppose we used Delegate or Method to Find:

//Ste#1 List of Name

List<string> names = new List<string>() { "Salman", "Noman", "Adam","man" };

//Ste#2 Using a Method that is invoked every time, in Step3

public bool EvaluteResult (string s)


return s.StartsWith("A");


//Step#3 Using List FindAll Method, that accept Predicate

List<string> matchedItem = names.FindAll(EvaluteResult);

Above Steps are fine, but a bit lengthy... So Developer wished that this Syntax become shortened a bit and there wished was granted, as Microsoft Introduced Anonymous Delegate.

2) When we used Anonymous Delegate:

//Ste#1 List of Name

List<string> names = new List<string>() { "Salman", "Noman", "Adam","man" };

//Ste#2 Anounymous Delegate, that is to create a Method inline with Deletgate

List<string> mathedItem = names.FindAll(delegate(string item) { return item.StartsWith("A"); });

Hmm, Developer where Happy, but in Step#2 above, Line of Code is still quite lengthy, so to further Shortened the Syntax Microsoft Introduced Lambda Expression.

1) When we used Lambda Expression:

//Ste#1 List of Name

List<string> names = new List<string>() { "Salman", "Noman", "Adam","man" };

//Ste#2 Using Lambda Expression to Shorten Anonymous delegate.

List<string> mathedItem = names.FindAll(item=> item.StartsWith("A"));

Note: To make things a bit easy, remmember “item=>” (on above) Represent input parameter as in any function/Method and “item.StartsWith("A")” Represent Body of Function/Method and they don’t require any decleration.

A Short Summary about Lambda Expression:

Basically Lambda are created mainly for LINQ as they evaluate certain value from collection quite easily as shown above, Lambda can used any where Pass In, Parameter Type is Predicate or Selector or Projection, However In our example shown above Pass in Parameter type is Predicate as names.FindAll accept Predicate.