Understanding Lambda expression in CSharp or VB.NET?

0 votes
asked Jul 16, 2013 in C#.NET by Vinith

Need help to understand what is Lambda expression? How do I use it in my application? What is the meaning of the below code if I say Employee is a table in SQL Server that has all employees of the organization.

context.Employee.Where(x => x.IsManager);
Share

1 Answer

+1 vote
answered Jul 17, 2013 by Aadhira (1,213 points)
selected Jul 18, 2013 by administrator
 
Best answer

Before I start explaining Lambda expressions, I would strongly suggest you to read about Delegates if you not have understanding about delegates.

Because Lambda expression are came from delegates. In fact, if I need to say correctly then, they came from anonymous methods. But anonymous method are came from delegate. You may be able to understand what I am saying, if you read through the examples below.

For example,

I will take a simple button click event and we see how we write it using regular delegate, then by anonymous method and finally by lambda expressions.

Regular Delegate Approach

this.btnStart.Click += new System.EventHandler(this.btnStart_Click);

private void btnStart_Click(object sender, EventArgs e)
{
    //Some code here
}

I think we all must have seen the above line of code in Winforms application.

The meaning of the above code is, whenever a user clicks on the btnStart button, "Button" class will raise an event.
Whenever the click event is raised, then the raise event will check whether any function that matches the delegate "System.EventHandler" is attached to this event to listen

If you look at the "System.EventHandler", below is the definition.

public delegate void EventHandler(object sender, EventArgs e);

It is simply a delegate with the name EventHandler and it accepts 2 parameter where first one is "object" type and the second one is "EventArgs" type and it does not return any value.

If you look at our "btnStartClick", the signature of that method (event handler) is same as "EventHandler" delegate. So, what we have done is, we have attached the "btnStartClick" event handler to the Click event of the button through "System.EventHandler" delegate.

So, when the button is clicked, click event will find this "btnStart_Click" method attached, so it will call that method.

Anonymous method:
In the previous example, we have created explicitly an event handler method to handle the click event. But when you use anonymous method, you do need to write a separate named method. Instead we do the below.

this.btnStart.Click += delegate(object source, EventArgs e)
            {
                //Some code here
            };

You are right. We have just removed the named method and put all its code in place of attaching to the event. Since the above code does not have any name we call it as Anonymous method.

We have used delegate keyword instead of method name and we passes the parameters same as the parameters passed in "btnStartClick" event handler, then copied the code block from "btnStartClick" to this delegate.

So, by using this approach we really not gained anything because we have just removed the name of the method. Otherwise, everything else is same.

To go step further, we will see the Lambda expression approach

Lambda Expression:

Now, we will modify the Anonymous methods to Lambda expression. For that

First remove the delegate keyword and then remove types of the parameter.
Finally use "=>" operator between the parameters and code block. Now it becomes like this.

this.btnStart.Click += (source, e) =>
            {
                //Some code here
            };

So, the meaning of this code is, we are doing the same thing what we did in the first approach. We are saying that, please call this block of code when a user click on the button.

Left hand side of "=>" operator will be the parameters passed to the method.
Right hand side of "=>" operator will be the code block which we use to right in the regular methods.
So, you can use the parameter inside code block if you need to.

Now lets jump into your sample code.

context.Employee.Where(x => x.IsManager);

The above code used context object, that is nothing but a sql connection object using entity framework used to query your database tables to do CRUD operations.

As you said Employee is a table and "Where" is a special LINQ operator used to find all matching objects which return true for the predicate we pass.

Predicate is nothing but the Lambda expression we pass to that "Where" operator.

Where(x => x.InManager)

Whenever we use "Where" on a collection of object (Employee is a collection right?), what it will do is, it will read items from that collection one by one and run the condition on that item. in your example, it will take each employee from the collection.

as I said, in Lambda expression, if you have something on the left hand side of the "=>", then it is parameter. So, that is nothing but a employee object.

RHS of "=>" is the code to execute. If you have not used "{}" around the code block you want to execute, then that means the code must be boolean expression.

context.Employee.Where(x => x.IsManager);

and

context.Employee.Where(x => { return x.IsManager });

both are same. So, expression in your example, go through each employee object from the context.Employees collection and validates that the employee is a manager by verifying IsManager flag value.

I hope you this example might give some idea about Lambda expression.

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...