Friday 18 October 2013

Expression Lambdas vs Statement Lambdas

Lambda expression is an inline delegate introduced with C # 3.0 language. It’s a concise way to represent an anonymous method. Lambda expressions are particularly helpful for writing LINQ query expressions.

The => operator has the same precedence as assignment (=) and is right-associative.

Expression Lambda

A lambda expression with an expression on the right side is called an expression lambda.

Syntax
(input parameters) => expression

The parentheses are optional only if the lambda has one input parameter; otherwise they are required. Two or more input parameters are separated by commas enclosed in parentheses:

(x, y) => x == y

Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you can specify the types explicitly as shown in the following example:

(int x, string s) => s.Length > x

Specify zero input parameters with empty parentheses:

() => SomeMethod()

Statement Lambda

A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:

Syntax
(input parameters) => {statement;}

Below example uses expression lambda and statement lambda to find even numbers from a List<int>

        List<int> numbers = new List<int>{1,2,3,4,5,6,7};
        var evens = numbers.FindAll(n => n % 2 == 0);
        var evens2 = numbers.FindAll((int n) => { return n % 2 == 0; });
Read More>>

dotnetperls/lambda

Exploring-Lambda-Expression-in-C#

No comments:

Post a Comment