Lambda Expression in LINQ


What is Lambda Expression

lambda expression is an anonymous function. Using lambda expression we can create function for delegate and we can also create expression tree type.

Syntax of Lambda Expression

Input parameter=>programming statements

Lambda Expression with Delegate

If you know how to use delegate then you know we have to pass the reference of method to that delegate which matches the signature. But when we use lambda expression we can give the definition of that method directly to the delegate which is as follows:-

Example of lambda expression

  
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//create a delegate which take one int as input and return one int
public delegate int Del_example(int x);

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //create object of delegate and instead passing the ref of method i simply pass
        //the complete definition using lambda expression
        Del_example cal_square = x => x * x;

        //execute the delgate
        int res=cal_square(5);
        Response.Write(res);
    }
}  

Lambda expression another example

In this example we are calculating the power using lambda expression
  
  using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//create a delegate which take one int as input and return one int
public delegate int Del_example(int x);

//create another delegate to calculate power
public delegate int del_Power(int b, int p);

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //create object of delegate and instead passing the ref of method i simply pass
        //the complete definition using lambda expression
        Del_example cal_square = x => x * x;

        //execute the delgate
        int res=cal_square(5);
        Response.Write(res);

        //this is another exampel of lembda expression 

        //power calculation
        del_Power dp = (b, p) => {

            //as you can see we create variable in lembda expression
            int data = 1;

            for (int i = 1; i < p; i++)
            {

                data = data * b;
           
            }
            return data;
        };

        int res_power = dp(3, 5);

        Response.Write(res_power);

    }
}  

No comments:

Post a Comment