How to: Create a Lambda Expression
A lambda expression is a function without a name that evaluates a single expression and returns its value.
To create a lambda expression
Within a method, in any situation where a delegate type could be used, type the keyword Function, as in the following example:
Dim add1 = Function
In parentheses, directly after Function, type the parameters of the function. Notice that you do not specify a name after Function.
Dim add1 = Function (num As Integer)
Following the parameter list, type a single expression as the body of the function. The value that the expression evaluates to is the value returned by the function. You do not use an As clause to specify the return type.
You call the lambda expression by passing in an integer argument.
Alternatively, the same result is accomplished by the following example:
A common use of lambda expressions is to define a function that can be passed in as the argument for a parameter whose type is Delegate. In the following example, the GetProcesses method returns an array of the processes running on the local computer. The Where method from the Enumerable class requires a Boolean delegate as its argument. The lambda expression in the example is sent in for that purpose. It returns True for each process that has only one thread, and those are selected in filteredQuery.
Sub Main() ' Create an array of running processes. Dim procList As Process() = Diagnostics.Process.GetProcesses ' Return the processes that have one thread. Notice that the type ' of the parameter does not have to be explicitly stated. Dim filteredList = procList.Where(Function(p) p.Threads.Count = 1) ' Display the name of each selected process. For Each proc In filteredList MsgBox(proc.ProcessName) Next End Sub
The previous example is equivalent to the following code, which is written in Language-Integrated Query (LINQ) syntax: