Books of .Net/Interview Questions Interview Questions and Answers Programs C# Concept OOPS Concept JOBS

Monday, August 14, 2017

Lambda Expressions in C#



Although anonymous methods are still part of C#, they have been largely superceded by a better approach: the lambda expression. It is not an overstatement to say that the lambda expression is one of the most important features added to C# .
Based on a distinctive syntactic element, the lambda expression provides a powerful alternative to the anonymous method. Although a principal use of lambda expressions is found when working with LINQ , they are also applicable to  delegates and events. 

Delegate. The delegate keyword denotes an anonymous function. After this keyword, we use a formal parameter list. We can omit the list if there are no parameters.

Anonymous functions. This term includes both delegates and lambda syntaxes. An anonymous function has no name. Perhaps it is running from the law.
Many developers regard lambda expressions as a complete improvement over (and replacement for) the delegate syntax.

use of lambda expressions 
A lambda expression is the second way that an anonymous function can be created. Thus, a lambda expression can be assigned to a delegate. Because a lambda expression is more streamlined than the equivalent anonymous method, lambda expressions are now the recommended approach in almost all cases.


The Lambda Operator
All lambda expressions use the lambda operator, which is =>.
 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.”

Lambda expressions are anonymous functions that contain expressions or sequence of operators. All lambda expressions use the lambda operator =>, that can be read as “goes to” or “becomes”. 

Expression Lambdas
Parameter => expression
Parameter-list => expression
Count => count + 2;
Sum => sum + 2;
n => n % 2 == 0


n => n % 2 == 1 
n is the input parameter
n % 2 == 1 is the expression
You can read n => n % 2 == 1 like: "input parameter named n goes to anonymous function which returns true if the input is odd".

The lambda operator => divides a lambda expression into two parts. The left side is the input parameter and the right side is the lambda body.

Why do we need lambda expressions? 

  • Reduced typing. No need to specify the name of the function, its return type, and its access modifier.
  • When reading the code, you don't need to look elsewhere for the method's definition.


Important points to remember while using lambda expressions
  • A lambda expression can return a value and may have parameters.
  • Parameters can be defined in a unlimited no of ways with a lambda expression.
  • If there is single statement in a lambda expression, there is no need of curly brackets whereas if there are multiple statements, curly brackets as well as return value are essential to write.
  • It is impossible to execute any unsafe code inside any lambda expression.
  • Lambda expressions are not meant to be used on the operator’s left side.

Example 1 - 
Step 1 - We have list of numbers from 1 to 6.
        List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };

Step 2 -  We want to find even numbers from list.
Code -
using System;
using System.Collections.Generic;
using System.Linq;
public static class demo
{
    public static void Main()
    {
        List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };
        List<int> evenNumbers = list.FindAll(x => x % 2 == 0);

        foreach (var num in evenNumbers)
        {
            Console.Write("{0} ", num);
        }
        Console.WriteLine();
        Console.Read();

    }
}

output - 2 4 6


Example 2 -
We create a collection, containing data from a certain class. In the example, from the class Car(with properties Name and Model), we want to get a list that contains all the car's names. With the keyword var, we tell the compiler to define the type of the variable depending on the result that we assigned on the right side of the equals sign.



using System;

using System.Collections.Generic;
using System.Linq;
class Car
{
    public string Name { get; set; }
    public int Model { get; set; }
}
class demo
{
    static void Main()
    {
        List<Car> car = new List<Car>() {
            new Car{ Name="Maruti",Model=1999 },
            new Car{Name="BMW",Model=2000},
            new Car{Name="TATA",Model=2001}
        };

        var names = car.Select(x => x.Name);
        foreach (var name in names)
        {
            Console.WriteLine(name);

        }
        Console.Read();
    }
}
OUTPUT - Maruti  BMW TATA

Example 3 -Here is an example that uses a statement lambda to compute and return the factorial of an int value:

Delegate IntOp takes one int argument and returns an int result.


Code -
using System;
delegate int IntOp(int end);
class StatementLambdaDemo
{
    static void Main()
    {
        // A statement lambda that returns the factorial
        // of the value it is passed.
        IntOp fact = n =>
        {
            int r = 1;
            for (int i = 1; i <= n; i++)
                r = i * r;
            return r;
        };
        Console.WriteLine("The factorial of 3 is " + fact(3));
        Console.WriteLine("The factorial of 5 is " + fact(5));
        Console.ReadKey();
    }
}

Output -
The factorial of 3 is 6
The factorial of 5 is 120

Note for Freshers - Please read all my blogs of oops,c#,interview questions to get easily jobs in Software , IT field as developer ,programmer.


You may also like





No comments :

Post a Comment