Wriju's BLOG

.NET, Cloud and everything

C# 3.0 Enhancements: Lambda Expression

After a pretty long time I am again back to the Blog business. During these days I was busy preparing myself on C# 3.0 for our ISV Developers. I started giving demos to them and during my study I found a good number of exciting features which C# 3.0 offers in a nutshell. I will talk about them one by one. Let’s start with Lambda expression.


 


Lambda Expressions are giving first class treatment to delegate and functions. When you are dealing with Lambda Expressions then you are surely dealing with Delegates.


 


Let’s assume this example.


 


//Array of integers


List<int> arrInt =


new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


 


//Using Predicate we are finding the even numbers


List<int> even1 =


arrInt.FindAll(new Predicate<int>(EvenGetter));


 


foreach(int i1 in even1)


    Console.WriteLine(i1);


 


Console.ReadKey();


 


This retrieves the even numbers from the collection. But you need another method


static bool EvenGetter(int i)


{


    return i % 2 == 0;


}


 


 


In C# 2.0 we have introduced little smarter way. You can add inline function using the keyword delegate. The code looks like,


 


//Using delegate keyword, more smarter way


List<int> even1 = arrInt.FindAll(delegate(int i2)


{ return i2 % 2 == 0; });


 


This does not require any extra function in the application. But it is still painful.


 


Lambda Expression helps us to write code like.


 


//Using Lambda Expression


List<int> even1 = arrInt.FindAll( x => x % 2 == 0);


 


This approach is without using delegate but the way of implementation much clean. In this syntax x => x % 2 == 0 can be changed to (int x) => x % 2 == 0


 


Namoskar!!!