Export (0) Print
Expand All

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

  1. 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

  2. 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)

  3. 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.

    Dim add1 = Function(num As Integer) num + 1
    

    You call the lambda expression by passing in an integer argument.

    ' The following line prints 6.
    Console.WriteLine(add1(5))
    
  4. Alternatively, the same result is accomplished by the following example:

    Console.WriteLine((Function(num As Integer) num + 1)(5))
    

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:

Sub Main()

    Dim filteredQuery = From proc In Diagnostics.Process.GetProcesses _
                        Where proc.Threads.Count = 1 _
                        Select proc

    For Each proc In filteredQuery
        MsgBox(proc.ProcessName)
    Next 
End Sub

Community Additions

ADD
Show:
© 2015 Microsoft