Lambda Expressions

Lambda expression provides a powerful alternative to the anonymous method. The principal use of lambda expressions is found when working with LINQ, but they are also applicable to delegates and events.

The Lambda Operator (=>)
All lambda expressions use the lambda operator (=>).This operator divides a lambda expression into two parts. On the left the input parameter (or parameters) is specified. On the right is the lambda body. The => operator is sometimes verbalized as “goes to” or “becomes.”

C# supports two types of lambda expressions – Expression Lambda and Statement Lambda. It is the lambda body that determines what type is being created.

Expression Lambda – If the lambda body consists of a single expression, then an expression lambda is being created. In this case, the body is free-standing — it is not enclosed between braces.
The expression on the right side of the => acts on the parameter (or parameters) specified by the left side. The result of the expression becomes the result of the lambda operator and is returned.
Syntax:
a) Single Parameter – param => expr
b) Multiple Parameter – (param-list) => expr

Here is a simple expression lambda: iIndex => iIndex + 2
Here iIndex is the parameter that is acted on by the expression iIndex + 2. Thus, the result is the value of iIndex increased by two.

Here is another example: iCount => iCount % 2 == 0
In this case, this expression returns true if iCount is even and false if it is odd.

Usage of Lambda Expression: To use a lambda expression involves two steps:
1) Declare a delegate type that is compatible with the lambda expression.
2) Declare an instance of the delegate, assigning to it the lambda expression.
Once this has been done, the lambda expression can be executed by calling the delegate instance. The result of the lambda expression becomes the return value.

Example:

// Use two simple lambda expressions.
using System;
// Declare a delegate that takes an int argument
// and returns an int result.
delegate int Increment(int v);
// Declare a delegate that takes an int argument
// and returns a bool result.
delegate bool IsEven(int v);
class SimpleLambdaDemo
{
  static void Main()
  {
    // Create an oIncrement delegate instance that refers to
    // a lambda expression that increases its parameter by 2.
    Increment oIncrement = count => count + 2;
    // Now, use the oIncrement lambda expression.
    Console.WriteLine("Use oIncrement lambda expression: ");
    int iIndex = -10;
    while(iIndex <= 0)
    {
      Console.Write(iIndex + " ");
      iIndex = oIncrement(iIndex); // increase x by 2
    }
    Console.WriteLine("\n");
    // Create an IsEven delegate instance that refers to
    // a lambda expression that returns true if its parameter
    // is even and false otherwise.
    IsEven oIsEven = n => n % 2 == 0;
    // Now, use the oIsEven lambda expression.
    Console.WriteLine("Use oIsEven lambda expression: ");
    for(int i = 1; i <= 10; i++)
    {
      if(oIsEven(i)) Console.WriteLine(i + " is even.");
    }
  }
}

The output is shown here:
Use oIncrement lambda expression:
-10 -8 -6 -4 -2 0
Use oIsEven lambda expression:
2 is even.
4 is even.
6 is even.
8 is even.
10 is even.


Statement Lambda – If the lambda body consists of a block of statements enclosed by braces, then a statement lambda is being created. A statement lambda can contain multiple statements and include such things as loops, method calls, and if statements.

Example:

// Demonstrate a statement lambda.
using System;
// Factorial takes one int argument and returns an int result.
delegate int Factorial(int iEnd);
class StatementLambdaDemo
{
  static void Main()
  {
    // A statement lambda that returns the factorial
    // of the value it is passed.
    Factorial oFactorial = iLimit =>
    {
      int iValue = 1;
      for(int i=1; i <= iLimit; i++)
      iValue = i * iValue;
      return iValue;
    };
    Console.WriteLine("The factorial of 3 is " + oFactorial(3));
    Console.WriteLine("The factorial of 5 is " + oFactorial(5));
  }
}

The output is shown here:
The factorial of 3 is 6
The factorial of 5 is 120

Q. How does the compiler know about the type of data used in a lambda expression?
A. The compiler infers the type of the parameter and the expression’s result type from the delegate type. Thus, the lambda parameters and return value must be compatible with the parameter type(s) and return type of the delegate.

Lambda Expressions



Lambda Expressions – What are they good for?


No comments:

Post a Comment