Lambda Expressions: Syntax
Posted
Sun, Oct 11 2009 14:02
by
Deborah Kurata
This post covers the syntax for lambda expressions. It uses the customer list defined in this prior post.
[To begin with an overview of lambda expressions, start here.]
The first example below uses the FirstOrDefault extension method on the Enumerable object to find the first customer that matches the defined expression. The FirstOrDefault method takes a delegate as a parameter and that delegate is defined with a lambda expression.
In C#:
' General syntax:
Customer foundCustomer =
custList.FirstOrDefault((Customer c) =>
c.CustomerId == 4);)
' With inferred typing:
var foundCustomer =
custList.FirstOrDefault(c => c.CustomerId == 4);)
The lambda expression in this example is as follows:
c => c.CustomerId == 4
The code begins with the set of parameters to the lambda expression. In this example, there is one parameter (c). The => is the “goes to” or lambda operator. The remainder of the code is the expression itself. In this case, checking for the item in the list where CustomerId is 4.
In VB:
' General syntax:
Dim foundCustomer as Customer = _
custList.FirstOrDefault(Function(c as Customer) _
c.CustomerId = 4)
' With inferred typing:
Dim foundCustomer = _
custList.FirstOrDefault(Function(c) _
c.CustomerId = 4)
The lambda expression in this example is as follows:
Function(c) c.CustomerId = 4
The code begins with the word “Function” along with the set of parameters to the lambda expression. In this example, there is one parameter (c). The remainder of the code is the expression itself. In this case, checking the item in the list where CustomerId is 4.
In either language, notice the shorter syntax with inferred typing. The compiler recognizes that the list contains customers, so it can infer the type of the parameter and the type of return value.
You can combine some of the extension methods to form more complex statements.
In C#:
var query = custList.FindAll(c =>
c.LastName.StartsWith(“K”)).OrderBy(c => c.FirstName));
In VB:
Dim query = custList.FindAll(Function(c) _
c.LastName.StartsWith(“K”)). _
OrderBy(Function(c) c.FirstName))
This code finds all of the entries that match the first lambda expression, basically all customers with a last name that begins with “K”. The code then performs an OrderBy using the second lambda expression, basically sorting the resulting list by first name.
The above examples demonstrate single-line lambdas. You can also use multi-line lambdas as shown in the example below.
In C#:
var foundCustomer =
custList.FirstOrDefault(c =>
{
Debug.WriteLine(c.LastName);
if (c.CustomerId == 4)
return true;
else
return false;
});
In VB:
Not available in VB9, coming in VB10.
Multi-line lambda expressions require the standard {} syntax to define the statement block. Whereas single-line lambda expressions automatically handle the return value for you, you have to handle it yourself in multi-line lambda expressions.
Enjoy!