Jul 29 2007

Lambda Expressions

Category: C# 3.0Bil@l @ 13:37

 1.
 Lambda Expressions have been introduced as an improvement
 to the anonymous methods in C# 2.0 as a way to make them
 more compact.

 2.
 Lambda expression consists of:
  . Parameter List
  . =>
  . Expression

 3.
 Parameters of Lambda Expression can be implicitly
 or explicitly typed. Ex:
  . (int i) => (i+1)
  . (i) => (i+1)

 4. You can have single or multiple parameters Ex:
  . (x,y) => return x*y

 5. If you want to pass a lambda expression with no parameters:
  . () => return "Empty Parameters";


Think of Lambda expressions as an anonymous method in a more compact style. Take this example:

Suppose we have a list of employees named "customers". You want to query this list using a System defined Extension method called "WHERE" as follows:

var query= customers.Where( c => c.Country == "Lebanon"; );

As you can see the above lambda expression is composed of:

1- c: Which is the input parameter
2- => token
3- c.Country == "Lebanon": this is the expression that will be applied to every record retrieved from the customers list. So, while the query is looping through the records of customers,
it will apply the lambda expression, if the result of the expression is true, then it will include the current record in the result of the query.

We could have done the same using Anonymous methods as in C# 2.0:

var query= customers.Where(
  delegate (Customer c) {
   return c => c.Country == "Lebanon";
  }
 );


Notice also that the lambda expression can be a series of statements and not only a single simple statement.

(x) => { Console.WriteLine("Hello World"); return 0; }

All of the above expressions could have been placed with the { and } too!

Hope this helps,
Regards

Tags:

Comments are closed