Sunday 2 June 2013

LINQ-Hour 4 Lambda Expression Part 1

LAMBDA Expression Part 1 

A 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 Example 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:-
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);
    }
}


Let’s take 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);

    }
}


In the next article I will discuss how to use lambda expression using LINQ

No comments:

Post a Comment