Geeks With Blogs
Create Fun Things - Samer's Developer Blog Development Blog for C#, .NET and Obj-C

Lambda expressions are yet another one of those things that took me a while to really embrace/ understand but once I did, I use them exclusively in LINQ.

The reason it took me a while to finally start using them is because every time I tried to read an explanation of them, the author got bogged down in a ridiculous amount of details and explanations that I either got lost, or just lost interest. Once I learned how to use them, I found it was easier to go back and re-read those explanations and understand what all was going on. In other words, I learned them in reverse (Practice –> Theory)

So that’s what I’ll attempt to do today in this blog post. I want to at least get the possible readers understanding how to use them in practical situations, then they can go off and read about the theory of them and how they work, etc.

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. But since you start with “from”, intellisense can do this:

image

Pretty cool. Okay, so going back to our 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);

That’s pretty cool. 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. Again, just to drill in the point, it’s like typing in:

var query = DataContext.PersonalMessages.Where(PersonalMessage=>PresonalMessage.ConvoID = ConvoID);

Now I want to get even faster with my method calling. Instead of defining a query, then returning it, or doing other things to it, I can easily chain things to it. Lets say I want to return a List of personal messages. I can now do:

List<PersonalMessage> myPersonalMessages = db.PersonalMessages
                .Where(m => m.ConversationID_FK == ConversationID)
                .ToList();

Awesome! Very easy. I can get even cooler now, all with the ease of dot notation. Lets say I want to orderit by the date the personal message was created. No problem, I can throw in an .OrderBy:

List<PersonalMessage> myPersonalMessages = db.PersonalMessages
    .Where(m => m.ConversationID_FK == ConversationID)
    .OrderBy(m=>m.DateCreated)
    .ToList();

Again, I’m creating a little “mini-method” that is passing in the personal message as m, and saying to order it by the date it was created. The possibilities are limitless here, because I can keep using intellisense to guide me through methods and I can chain just about any LINQ method here:

image

In the above query, I threw in a “ThenBy” statement to order by the author’s name after I ordered it by the date it was created. I can do all these method calls very easily using Lambda expressions, all with the help of intellisense, and all without verbose query writing. Very cool!

Hope this was helpful to those like me that struggled understanding how to use Lambda expressions.

Cheers,

samer paul

Posted on Thursday, September 24, 2009 10:32 AM | Back to top


Comments on this post: Practical Understanding of Lambda Expressions in C#/ Linq

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Very nice-n-helpful Post. Thank you!
Left by Sameer Joshi on Oct 06, 2009 7:22 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Great Job. Really cool explanation.
Left by Sri on Mar 16, 2011 1:06 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Nice Job..
Best lambda explanation I have found. I felt exactly the same way you did about them. Thanks for taking the time to blog this info!!
Left by Steve on Nov 16, 2011 9:24 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Simple n sweet
Left by Neeraj on Feb 18, 2012 5:19 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Nice and simple so how do i display returned data to c# console application
Left by JM on Feb 28, 2012 11:36 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Thank for taking the time to compose this. Like you I have been finding that other explanations get side tracked into way too much detail.

This is the best explanation I have seen so far!
Left by Russell on Mar 15, 2012 7:30 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Thank you for the great explanation. It really makes sense now.
Left by Shaygen on Mar 21, 2012 2:31 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Great Job. Helped me a lot!
Left by Dave Smith on Nov 09, 2012 10:36 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Thanks, this is one of the best explanations I have seen so far. I had struggled with understanding lambdas, and this helped a lot.
Left by Paul B on Feb 18, 2013 8:09 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Something short and to the point!
Left by Duy on Feb 25, 2013 9:04 PM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Nice tutorial. Thanks for posting it.
Left by BashaBill on Jun 28, 2013 3:58 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
This seems somewhat odd to me... in this example you could still use linq without the select line and it'd return an instance of the entity. It's shorter that way too. Perhaps your example oversimplifies something to show lambdas and I'm missing something. I come from a SQL background before coming to .NET, so that could also account for my bias against thinking lambdas look human-readable.
Left by Dan on Apr 22, 2014 1:10 PM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
Great article for beginner as far as revisal.
Left by Raveendra Bj on Oct 20, 2015 5:08 AM

# re: Practical Understanding of Lambda Expressions in C#/ Linq
Requesting Gravatar...
wonderful article, thank you
Left by Boitumelo on Dec 03, 2015 2:37 AM

Your comment:
 (will show your gravatar)


Copyright © samerpaul | Powered by: GeeksWithBlogs.net