LINQ to SQL Basics – Part 4 (Lambda Expressions)

Today I will be showing a few short examples of using Lambda expressions. Lambda expressions is nothing new, it also exists in other languages and been used for quite a while. Lambda expressions are based on Lambda Calculus. You can do some research on Lambda Calculus on Wikipedia (www.wikipedia.org). I recommend reading Chapter 5 (Understanding Lambda Expressions and Closures) of SAMS LINQ Unleashed for C# by Paul Kimmel.

By using Lambda expressions we can write our LINQ queries more compact. We all love less code, don’t we?

Look at the following simple select:

var q = from ct in db.Customers


select ct;

can be written using a Lambda expression as follow:

var q = db.Customers.Select(ct => ct);

The same SQL query is constructed for both of the selects. Now let’s build the query up a bit. We adding a ‘Where’ to the select statement. This is how it will look now:

var q = from ct in db.Customers


where ct.CustomerID == “ALFKI”


select ct;

This is how the Lambda expression will look like:

var q = db.Customers.Where(ct => (ct.CustomerID == “ALFKI”));

Lambda expressions can get quite complicated the more complex your query gets. Let’s look at the next query. Here we are selecting all the orders for CustomerID = “ALFKI”:

var f = from ct in db.Customers


join o in db.Orders


on ct.CustomerID equals o.CustomerID


where ct.CustomerID == “ALFKI”


select o;

Now writing this as a Lambda expression gets more involved:

var g = db.Customers

.Where(ct => ct.CustomerID == “ALFKI”)

.Join(db.Orders, ct => ct.CustomerID, o => o.CustomerID, (ct, o) => o);

Using Lambda Expressions does take some time to understand and grow on you.

 

 

Advertisement
Published in: on April 14, 2009 at 8:23 am  Leave a Comment  
Tags: , ,

The URI to TrackBack this entry is: http://mvkatredleaf.wordpress.com/2009/04/14/linq-to-sql-basics-%e2%80%93-part-4-lambda-expressions/trackback/

RSS feed for comments on this post.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.