**“Lambda expression is simply a Method.”**

## Syntax of Lambda Expression

*Input Parameters => Expression/Statement Block;* Left hand side of expression contains the zero or more parameters followed by Lambda operator ‘=>’ which is read as “goes to” and right hand side contains the expression or Statement block.

This Lambda expression is read as “x goes to x times 2”. Lambda Operator “=>” has sameprecedence as assignment “=” operator. This simple expression takes one parameter “x” and returns the value “x*2”.

## Parameters Type

The parameters of the lambda expression can be explicitly or implicitly typed. For example(int p) => p * 4; // Explicitly Typed Parameter

q => q * 4; // Implicitly Typed Parameter

Explicit typed parameter is same as parameters of method where you explicitly specified the type of parameter. In an implicit typed parameter, the type of parameter inferred from the context of lambda expression in which it occurs.

## Use simple Lambda Expression

Here is simple example of Lambda Expression which returns a list of numbers greater than 8.int[] numbers = {1,2,3,4,5,6,7,8,9,10 };You can also use anonymous method for returning same list.

var returnedList = numbers.Where(n => (n > 8));

int[] numbers = {1,2,3,4,5,6,7,8,9,10 };

var returnedList = numbers.Where(delegate(int i) { return i > 8; });

## Use Statement Block in Lambda Expression

Here is simple example to write statement block in the lambda expression. This expression returns list of numbers less than 4 and greater than 8.

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var returnedList = numbers.Where(n =>

{

if (n < 4)

return true;

else if (n > 8)

return true;

return false;

}

);

## Use Lambda with More then one Parameter

You can also write lambda which takes more than one parameters. Here is an exampleof lambda which adds two integer numbers.

delegate int AddInteger(int n1, int n2);

AddInteger addInt = (x, y) => x + y;

int result = addInt(10,4); // return 14

## Use Lambda with Zero parameter

Here is an example of lambda which take no parameter and returns new Guid.delegate Guid GetNextGuid();

GetNextGuid getNewGuid = () => (Guid.NewGuid());

Guid newguid = getNewGuid();

## Use Lambda that return Nothing

You can also write lambda which returns void. Here is an example that lambda is only showing message and return nothing.

delegate void ShowMessageDelegate();

ShowMessageDelegate msgdelegate = () => MessageBox.Show("It returns nothing.");

msgdelegate();

## No comments:

## Post a Comment