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:
- static void Main(string[] args)
- {
- List < int > numbers = new List < int > ()
- {
- 1,2,3,4,5,6,7,8,9,10
- };
- List < int > oddNumbers = numbers.FindAll(x => x % 2 != 0).ToList();
- List < int > evenNumbers = numbers.FindAll(x => x % 2 == 0).ToList();
- Console.WriteLine("List of Odd Numbers is");
- foreach(int ab in oddNumbers)
- {
- Console.WriteLine(ab);
- }
- Console.WriteLine("List of Even Numbers is");
- foreach(int ab in evenNumbers)
- {
- Console.WriteLine(ab);
- }
- Console.ReadKey();
- }
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:
- class Program
- {
- delegate double del(int x);
- static void Main(string[] args)
- {
- del del1 = (x) => x * x;
- del del2 = (x) => Math.Sqrt(x);
- List < int > numbers = new List < int > ()
- {
- 1,2,3,4,5,6,7,8,9,10
- };
- Console.WriteLine("Number Square SquareRoot");
- foreach(int ab in numbers)
- {
- Console.WriteLine("{0} {1} {2}", ab, del1(ab), del2(ab));
- }
- Console.ReadKey();
- }
- }

Example:
- static void Main(string[] args)
- {
- Func < int, int > square = x => x * x;
- Func < int, int, int > sum = (x, y) => x + y;
- Func < int, int, int > sub = (x, y) => x - y;
- Func < int, int, int > mul = (x, y) => x * y;
- Func < int, int, int > div = (x, y) => x / y;
- int a = 10;
- int b = 5;
- Console.WriteLine(square.Invoke(a));
- Console.WriteLine(square.Invoke(b));
- Console.WriteLine(sum.Invoke(a, b));
- Console.WriteLine(sub.Invoke(a, b));
- Console.WriteLine(mul.Invoke(a, b));
- Console.WriteLine(div.Invoke(a, b));
- Console.ReadKey();
- }





Santhakumar MunuswamyPosted Feb 12, 2016, 11:34 PM
Thanks for nice share