Lambda Expression In C#

The concept of lambda expression was introduced in C# 3.0 . The term "Lambda expression" has derived its name from ‘lambda’ calculus, which in turn is a mathematical notation applied for defining functions. A lambda expression is an anonymous function and it is mostly used to create delegates in LINQ. At compile time all the lambda expressions are converted into anonymous methods according to lambda expression conversion rules. Lambda expressions are similar as LINQ equation’s executable part that translate logic in a way at run time so it can pass on to the data source conveniently.

Some advantages of lambda expression are that it allows us to write a method in the same place you are going to use it, especially when we are going to use a method only a single time. In such a way it saves our effort of declaring and writing a separate method to the containing class. Lambda expressions are not just limited to find applications in LINQ only, lambda expressions can also used for further types of calculation.

Syntax:

(input parameters) => expression or statement block

The left side of the lambda operator ("=>") represents the arguments to the method and the right side is the method body.

Let us take some Example:

Example 1:

  1. static void Main(string[] args)  
  2. {  
  3.     List < int > numbers = new List < int > ()  
  4.     {  
  5.       1,2,3,4,5,6,7,8,9,10  
  6.     };  
  7.     List < int > oddNumbers = numbers.FindAll(x => x % 2 != 0).ToList();  
  8.     List < int > evenNumbers = numbers.FindAll(x => x % 2 == 0).ToList();  
  9.     Console.WriteLine("List of Odd Numbers is");  
  10.     foreach(int ab in oddNumbers)  
  11.     {  
  12.         Console.WriteLine(ab);  
  13.     }  
  14.     Console.WriteLine("List of Even Numbers is");  
  15.     foreach(int ab in evenNumbers)  
  16.     {  
  17.         Console.WriteLine(ab);  
  18.     }  
  19.     Console.ReadKey();  
  20.  

Output:

Output

In the above example we created a list of integer type(numbers) and using the lambda expression we separated out even and odd numbers from the list.

Delegates with Lambda Expression:
  1. class Program  
  2. {  
  3.     delegate double del(int x);  
  4.     static void Main(string[] args)  
  5.   {  
  6.         del del1 = (x) => x * x;  
  7.         del del2 = (x) => Math.Sqrt(x);  
  8.         List < int > numbers = new List < int > ()   
  9.         {  
  10.         1,2,3,4,5,6,7,8,9,10  
  11.         };  
  12.         Console.WriteLine("Number Square SquareRoot");  
  13.         foreach(int ab in numbers)   
  14.         {  
  15.             Console.WriteLine("{0} {1} {2}", ab, del1(ab), del2(ab));  
  16.         }  
  17.         Console.ReadKey();  
  18.     }  
  19.  
Output:

Output

Example:
  1. static void Main(string[] args)   
  2. {  
  3.     Func < intint > square = x => x * x;  
  4.     Func < intintint > sum = (x, y) => x + y;  
  5.     Func < intintint > sub = (x, y) => x - y;  
  6.     Func < intintint > mul = (x, y) => x * y;  
  7.     Func < intintint > div = (x, y) => x / y;  
  8.     int a = 10;  
  9.     int b = 5;  
  10.     Console.WriteLine(square.Invoke(a));  
  11.     Console.WriteLine(square.Invoke(b));  
  12.     Console.WriteLine(sum.Invoke(a, b));  
  13.     Console.WriteLine(sub.Invoke(a, b));  
  14.     Console.WriteLine(mul.Invoke(a, b));  
  15.     Console.WriteLine(div.Invoke(a, b));  
  16.     Console.ReadKey();  
  17. }  
Output:

output

Expression Tree:

Lambda expressions are also used inthe construction of expression tree extensively. An expression tree is similar to a data structure resembling a tree in which every node is itself an expression like a method call, or it can be a binary operation .

Example:
  1. static void Main(string[] args)  
  2. {  
  3.     List < int > numbers = new List < int > ()  
  4.     {  
  5.        1,2,3,4,5,6,7,8,9,10  
  6.     };  
  7.     foreach(int ab in numbers.Where(x =>  
  8.     {  
  9.         if (x % 3 == 0)  
  10.             return true;  
  11.         else if (x % 5 == 0)  
  12.             return true;  
  13.         else  
  14.             return false;  
  15.     }))   
  16.     {  
  17.         Console.WriteLine(ab);  
  18.     }  
  19.     Console.ReadKey();  
  20. }  
Output:

output

The below code also generate the same result,
  1. static void Main(string[] args)  
  2. {  
  3.     List < int > numbers = new List < int > ()  
  4.     {  
  5.        1,2,3,4,5,6,7,8,9,10  
  6.     };  
  7.     foreach(int ab in numbers.Where(x =>  
  8.         x % 3 == 0 ||  
  9.         x % 5 == 0  
  10.     ))  
  11.     {  
  12.         Console.WriteLine(ab);  
  13.     }  
  14.     Console.ReadKey();  
  15. }  
Lambda Expression with Multiple Statement:

We can wrap expressions in curly braces if you want to have more than one statement in the body.
  1. static void Main(string[] args)  
  2. {  
  3.     List < int > numbers = new List < int > ()  
  4.     {  
  5.       1,2,3,4,5,6,7,8,9,10  
  6.     };  
  7.     foreach(int ab in numbers.Where(x =>   
  8.     {  
  9.         Console.WriteLine("Number is {0}", x);  
  10.         Console.WriteLine("Sqrt of Value is {0}", Math.Sqrt(x));  
  11.         return x % 3 == 0 || x % 5 == 0;  
  12.     }))  
  13.     {  
  14.         Console.WriteLine("Returned Number is {0}", ab);  
  15.     }  
  16.     Console.ReadKey();  
  17. }  
Output:

output

Local Variable:

You can declare a variable in the expression body to use it anywhere in the expression body; this variable is only visible with expression body. We can’t access this variable outside the body of expression.

Example:
  1. static void Main(string[] args)  
  2. {  
  3.     List < int > numbers = new List < int > ()   
  4.     {  
  5.        1,2,3,4,5,6,7,8,9,10  
  6.     };  
  7.     foreach(int ab in numbers.Where(x =>  
  8.     {  
  9.         int number = 5;  
  10.         return x > number;  
  11.     }))   
  12.     {  
  13.         Console.WriteLine("Returned Number is {0}", ab);  
  14.     }  
  15.     Console.ReadKey();  
  16. }  
Output:

output

Points to Consider:
  1. Lambda Expression is a shorter way of representing anonymous method.
  2. Lambda Expression can have zero or more parametes.
  3. Lambda expressions themselves do not have type, so CLR doesn’t support the concept of Lambda expression.
  4. Variables defined within a lambda expression are accessible only within the body of lambda expression.
  5. Lambda expression can have multiple statements in body expression in curly brackets {}.
  6. With in lambda expressions, it is possible to access variables present outside of the lambda expression block by a feature known as closure but vice versa is not possible.
  7. Unsafe code inside any lambda expression can’t be used.
  8. The local variable in lambda expressions is not to be garbage collected unless the delegate referencing the same becomes eligible for the act of garbage collection.
  9. Lambda expressions can also use with Func and Action delegates.