C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: Actions are like Subs in that they return no values, so we use the Sub keyword to specify an Action type.
SubHere: We create 2 Funcs and store them in local variables. We could pass these as arguments, or use the lambda directly as arguments.
VB.NET program that uses Func
Module Module1
Sub Main()
' Return an Integer with no arguments.
Dim test As Func(Of Integer) = Function() 10
Dim result = test.Invoke()
Console.WriteLine($"TEST RESULT: {result}")
' Return an Integer with a String argument.
' ... Returns the string length multiplied by 2.
Dim test2 As Func(Of String, Integer) = Function(x) x.Length * 2
Dim result2 = test2.Invoke("bird")
Console.WriteLine($"TEST2 RESULT: {result2}")
End Sub
End Module
Output
TEST RESULT: 10
TEST2 RESULT: 8
And: The Action is specified with a 1-line Sub. It returns no value. Instead it just calls Console.WriteLine.
VB.NET program that uses Action
Module Module1
Sub Main()
' Use Sub to create an action.
Dim test As Action(Of Integer, Integer) = Sub(x, y) Console.WriteLine("X is {0}, Y is {1}", x, y)
' Call the Action 3 times.
test.Invoke(10, 20)
test.Invoke(20, 30)
test.Invoke(30, -1)
End Sub
End Module
Output
X is 10, Y is 20
X is 20, Y is 30
X is 30, Y is -1
Here: We see 2 Predicates. The first tells us whether an integer is positive—it returns True if the value is greater than or equal to 0.
VB.NET program that uses Predicate
Module Module1
Sub Main()
' This Predicate receives an Integer, and returns a Boolean.
' ... It tells us if an Integer is positive.
Dim isPositive As Predicate(Of Integer) = Function(x) x >= 0
If isPositive.Invoke(10) Then
Console.WriteLine("NUMBER IS POSITIVE")
End If
' This Predicate receives a String.
' ... It returns true if the string is short (less than 10 chars).
Dim isShortString As Predicate(Of String) = Function(value) value.Length <= 9
If isShortString.Invoke("this is a long string") Then
' This is not reached.
Console.WriteLine("NOT REACHED")
End If
End Sub
End Module
Output
NUMBER IS POSITIVE
Here: We use a Lambda expression to create a Predicate that returns True when a String begins with the letter F.
StartsWith, EndsWithResult: The first string that begins with the letter F, "frog," is returned by the FirstOrDefault Function. The Predicate worked.
VB.NET program that uses Predicate as argument, LINQ
Module Module1
Sub Main()
Dim values() As String = {"bird", "frog", "dog", "cat"}
' Use Predicate to find first item starting with lowercase F.
Dim firstLetterF = values.FirstOrDefault(Function(x) x.StartsWith("f"))
' Result.
Console.WriteLine("FIRST ITEM STARTING WITH F: {0}", firstLetterF)
End Sub
End Module
Output
FIRST ITEM STARTING WITH F: frog