C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The lambda expressions are found after the equals sign and start with the Function or Sub keywords.
Info: A Function is a method that returns a value. In contrast a Sub returns no value.
VB.NET program that uses Func with 2 types
Module Module1
Sub Main()
' Lambda expression that receives Integer, returns Integer.
Dim func1 As Func(Of Integer, Integer) =
Function(value As Integer)
Return value + 1
End Function
' Use Func.
Console.WriteLine(func1.Invoke(4))
End Sub
End Module
Output
5
VB.NET program that uses Func with 3 types
Module Module1
Sub Main()
' Lambda expression that receives two Integers, returns Integer.
Dim func2 As Func(Of Integer, Integer, Integer) =
Function(value As Integer, value2 As Integer)
Return value * value2
End Function
' Use the function.
Console.WriteLine(func2.Invoke(2, 3))
End Sub
End Module
Output
6
VB.NET program that uses short lambda syntax
Module Module1
Sub Main()
' Lambda expression that receives Integer, returns String.
' ... Short syntax.
Dim func3 As Func(Of Integer, String) = Function(x) (x + 1).ToString()
' Call the lambda.
Console.WriteLine(func3.Invoke(3))
End Sub
End Module
Output
4
VB.NET program that uses Sub lambda
Module Module1
Sub Main()
' Lambda expression that returns void.
Dim action1 As Action =
Sub()
Console.WriteLine("action1")
End Sub
' Use Action instance.
action1.Invoke()
End Sub
End Module
Output
action1
Tip: With lambdas, we can pass a Function argument (a higher-order procedure) directly to these methods to sort collections.
However: We sort the Strings in the array by their lengths. We do this with a special lambda expression that uses CompareTo.
VB.NET program that sorts with lambda Function
Module Module1
Sub Main()
Dim items() As String = {"cat", "mouse", "lion"}
' Use lambda expression to specify Comparison for Array.Sort.
Array.Sort(items, Function(a As String, b As String)
Return a.Length.CompareTo(b.Length)
End Function)
' Loop over sorted array.
For Each item As String In items
Console.WriteLine(item)
Next
End Sub
End Module
Output
cat
lion
mouse
And: We can use an AddressOf-based expression anywhere a lambda expression might be used.
FindIndex: Here I use FindIndex, part of the List class, with an AddressOf reference to an Odd() function.
VB.NET program that uses AddressOf
Module Module1
Function Odd(ByVal value As Integer) As Boolean
' Return true if not even number.
Return Not value Mod 2 = 0
End Function
Sub Main()
Dim values As List(Of Integer) = New List(Of Integer)
values.Add(10)
values.Add(13)
values.Add(20)
' Find first odd number's index.
Dim i As Integer = values.FindIndex(AddressOf Odd)
Console.WriteLine(i)
End Sub
End Module
Output
1
Tip: They are a special syntax form in the VB.NET language. They allow us to write more concise, clearer programs.
List: Lambda expressions can be used as arguments to List methods (Sort, Find).
List Find, FindIndex