|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
Declares the parameters and code that define a lambda expression.
A lambda expression is a function without a name that calculates and returns a single value. You can use a lambda expression anywhere you can use a delegate type, except as an argument to RemoveHandler. For more information about delegates, and the use of lambda expressions with delegates, see Delegate Statement and Relaxed Delegate Conversion.
Lambda Expression Syntax
The syntax of a lambda expression resembles that of a standard function. The differences are as follows:
A lambda expression does not have a name.
Lambda expressions cannot have modifiers, such as Overloads or Overrides.
Lambda expressions do not use an As clause to designate the return type of the function. Instead, the type is inferred from the value that the body of the lambda expression evaluates to. For example, if the body of the lambda expression is Where cust.City = "London", its return type is Boolean.
The body of the function must be an expression, not a statement. The body can consist of a call to a function procedure, but not a call to a sub procedure.
There is no Return statement. The value returned by the function is the value of the expression in the body of the function.
There is no End Function statement.
Either all parameters must have specified data types or all must be inferred.
Optional and Paramarray parameters are not permitted.
Generic parameters are not permitted.
As a result of these restrictions, and of the ways in which lambda expressions are used, they usually are short and uncomplicated.
The following examples show two ways to create simple lambda expressions. The first uses a Dim to provide a name for the function. To call the function, you send in a value for the parameter.
Alternatively, you can declare and run the function at the same time.
Lambda expressions underlie many of the query operators in Language-Integrated Query (LINQ), and can be used explicitly in method-based queries. The following example shows a typical LINQ query, followed by the translation of the query into method format.
Dim londonCusts = From cust In db.Customers Where cust.City = "London" Select cust ' This query is compiled to the following code: Dim londonCusts = db.Customers _ .Where(Function(cust) cust.City = "London") _ .Select(Function(cust) cust)