.Net :Lambda expression
Lambda expression was introduced in C# 3.0 and .Net framework 3.5. The Lambda expressions are the easiest and shortest way of writing anonymous methods.
Lambda Expression have some special syntax represented by following:-
(parameters) => expression or block-of-statement
=> is a lambda operator whose left side are the arguments to the anonymous method and right side is the method body of anonymous method.
For e.g: x => x * x;
Important points about Lambda expression.
-
The lambda expression can be parameterless or can have multiple parameters.
For e.g:
Parameterless Lambda expression
() => Console.WriteLine("Parameter less lambda expressions)
Lambda expression with multiple parameters.
Func sum = (x,y)=>(x+y)
- The method body of Lambda expression can contain multiple statement.
For e.g: (x,y) =>
{
Console.WriteLine("Multiple statements in the method body of Lambda Expression");
Return x >= y;
}
Example to demonstrate Lambda Expression:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPattern
{
class Program
{
//Find Even Number using Lambda expression
static void Main(string[] args)
{
// A List of integers called num id defined
List<int> num = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
//
var evennumbers = num.FindAll(x => x % 2 == 0);
Console.WriteLine("The Even numbers are:");
foreach (int n in evennumbers)
{
Console.WriteLine(n);
}
Console.ReadLine();
}
}
}
Output:
The Even numbers are:
2
4
6
Lambda expression is frequently used for creating delegates in LINQ i.e they filter out specific data from list of data and use specific data in LINQ operation. It is used in various areas like linq to sql, linq to xml etc. The places where method is to be used only once there methods can be created through Lambda expression. The method definition through lambda expression is short thus saving effort of declaring and defining a separate method in container class
0 Comment(s)