Tom Stickel

Thoughts on Software Engineering
posts - 15 , comments - 3 , trackbacks - 0

LINQ Query and Lambda Expressions


Lambda expressions are a powerful tool to writing quick, concise code. They can be used in numerous situations, most notably in conjuction with LINQ statements.

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => y * z is read “x goes to y times z.”

Here’s how a typical LINQ query looks like without using lambda expressions:

var query = from m in db.PersonalMessages
where m.ConversationID_FK == ConversationID
select m;

Okay, not bad. It looks like a SQL query in reverse (i.e. you start off with “from” and end with “select”). This is so that intellisense can help you out—if you started with select, it would have on idea where you were going with the query.
we are selecting PersonalMessages where the ConversationID is equal to some value passed into the method. The query itself is kinda verbose, and I like to keep my code short and sweet, so how do I re-write this using lambda expressions? Here is the code, and then we’ll break it down:
var query = db.PersonalMessages
.Where(m => m.ConversationID_FK == ConversationID);

We got rid of “select’”, “from” and “in”, etc. Cleaned it up quite a bit. What all is happening though? Basically it’s written out like:

My Query = Get Personal Messages from my data context Where the ConversationID is equal to this #.

In other words, it reads exactly like it does in the first written out query, but it’s done faster. The where statement is like a mini-method. You’re defining some variable M (you can use any letter, I always use m for the sake of convention in my code) and then in this case you’re giving m some condition to work with.
You’re basically saying, define m real quick (m=>) as a stand-in for PersonalMessage. Then only return PersonalMessages where m’s ConversationID is equal to some value. 

Print | posted on Saturday, February 4, 2012 2:11 PM |

Feedback

Gravatar

# re: LINQ Query and Lambda Expressions

really helpful post clear the confusion in linq and lambda working functionality.
thanks a lot.
2/7/2014 3:09 AM | Deep
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: