Lambda expressions in VB are more verbose than their C# equivalent. You define a Lambda expression by using just the Function keyword the, the argument parameters, optionally the data type, and a statement that returns a value. The is no function name, no return type specified—the return type is implicit—and no Return keyword or End Function line. A Lambda expression must be a Function (not a Sub), and syntactically they look like compressed functions. Similar to the help file’s example here is a simple Lambda Expression that adds sales tax to a value.
Function(value As Decimal, tax As Decimal) _
value * (1 + tax)
You could certainly define a regular function, but Lambda expressions have some utilities that regular functions won’t support. You can’t define a nested function, but with Lambda expressions you can define a Lambda expression—a function for all intents and purposes—inside of another function. Nesting functions is probably not that useful in and of itself. More importantly Lambda expressions can be used to support a flexible style of programming by permitting you to pass Lambda functions as arguments to other functions, in effect, changing the behavior of the called function. Listing 1 demonstrates how to invoke the extension method Where—for IEnumerable(Of T) types. The Where method accepts a generic delegate Func(Of String, Boolean) which can be satisfied by a Lambda expression.
Listing 1: The Lambda expression in the Where method accepts a string and returns a Boolean indicating if the input string starts with the letter ‘A’.
Module Module1
Sub Main()
Dim names() As String = {"Paul", "Noah", _
"Alex", "Ashton"}
Dim NamesThatStartWithA = _
names.Where(Function(n) n.StartsWith("A"))
For Each name In NamesThatStartWithA
Console.WriteLine(name)
Next
Console.ReadLine()
End Sub
When you see methods that have arguments like predicate As System.Func(Of String, Boolean) then you know that you can use a Lambda expression. You can also assign a Lambda expression to a local variable and pass the variable to satisfy the argument. Of course part of the benefit of things like Lambda expressions is to compact code. Listing 1 can be re-written without the extra local variable, NamesThatStartWithA, as demonstrated in Listing 2.
Listing 2: Tighten the code up, which of course is a benefit of Lambda expressions-doing more with less.
Module Module1
Sub Main()
Dim names() As String = {"Paul", "Noah", _
"Alex", "Ashton"}
For Each name In names.Where(Function(n) n.StartsWith("A"))
Console.WriteLine(name)
Next
Console.ReadLine()
End Sub
Have fun with Lambda expressions There are a clever idiom rediscovered-probably by a math major at Microsoft-based on a 1930s notation of the same name. (The C# notation is closer to the mathematical notation.) To explore uses for Lambda expressions look at some code you have already written a rewrite it using Lambda expressions where you can.