Pranay Rana: Lambda Expressions

Wednesday, November 17, 2010

Lambda Expressions

What is Lambda expression ?
  • Lambda expression is replacement of the anonymous method avilable in C#2.0 Lamda expression can do all thing which can be done by anonymous method.
  • Lambda expression are sort and function consist of single line or block of statement.
Lambda expression syntax

=> is lambda expression operator which indicate that the code is lambda expression.
( param ) => expr(int x) = > { return x + 1 };
or
param => exprx=> x + 1;>
Note :
Here param is option you can also write as below
()=> Console.WriteLine()

Use of Lambda expression
Consider programmer where I have to find list of all even number from the list of interger.
List<int> 
lstNumber = new List<int>();
lstNumber.Add(20)
lstNumber.Add(1);
lstNumber.Add(5);
lstNumber.Add(26);

   C#2.0 by using anonymous method
List<int> even = 
    lstNumber.FindAll( delegate(int i) { if(i%2==) return i; }
   But for the C#3.0 with the lambda expression it will
List<int> even 
    = lstNumber.FindAll( i => (i%2) ==0 }  

As we can see the lambda expression are replacement of the anonymous method. But it more use full when you are playing with the objects collection and using linq in your application.

Consider a case where you have set of CustomerOrder(s) and you have to find out the orders which are having process status completed.

  Linq quey:
var order 
  = for o in orders where o.ProcessStatus
       = ProcessStatus.Completed select o;

  But with Lambda expression combine with the extension method where  
var order 
  = orders.where( o=> o.ProcessStatus  = ProcessStatus.Completed); 

Summary

Lambda expression one of the cool feature of the C#3.0 which replaces the anonymous method of C#2.0 and also more important to support LINQ.


2 comments: