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.