VB.NET List Find and Exists ExamplesUse the Find and Exists Functions with Predicate arguments on the List type.
List, Find. The List Find Function receives a Predicate argument. This argument tests elements to see if they match. Find then returns the element that first matches your Predicate.
Meanwhile, the Exists Functions like the Find Function but it returns true or false if an element exists. With Find and Exists, we replace iterative loops with single Function call.
Find example. We create a List of 3 Integers—this is the List we will search. We then invoke the Find function on this list with a lambda expression argument.
Find In this call to Find, we specify a lambda expression that returns True if the element is greater than 20.
FindLast This method searches from the end of the list, not the start. It is like LastIndexOf.
VB.NET program that uses Find
Module Module1 Sub Main() Dim list As List(Of Integer) = New List(Of Integer)({19, 23, 29}) ' Find value greater than 20. Dim val As Integer = list.Find(Function(value As Integer) Return value > 20 End Function) Console.WriteLine(val) End Sub End Module
FindIndex. This function works the same way as Find except it returns the index of the match, not the match itself. You should assign an Integer Dim to its result.
Not found If no match is found, FindIndex returns -1. We must test for this value if the element can possibly not exist.
VB.NET program that uses FindIndex
Module Module1 Sub Main() Dim list As List(Of String) = New List(Of String)({"bird", "cat", "car"}) ' Find index of first string starting with "c." Dim index As Integer = List.FindIndex(Function(value As String) Return value(0) = "c"c End Function) Console.WriteLine("FIRST C: {0}", index) End Sub End Module
Exists. This Function is just like Find—it accepts a Predicate argument. But it returns a True or False (Boolean) value instead of a List. If a matching element Exists, it returns True.
VB.NET program that uses List Exists
Module Module1 Sub Main() Dim list As List(Of Integer) = New List(Of Integer)({20, -1, 3, 4}) ' See if a negative number exists. Dim result = list.Exists(Function(value As Integer) Return value < 0 End Function) Console.WriteLine("EXISTS: {0}", result) ' See if a huge number exists. result = list.Exists(Function(value As Integer) Return value >= 1000 End Function) Console.WriteLine("EXISTS: {0}", result) End Sub End Module
A review. The List Find functions help us search List data. You can search from the beginning with Find and FindIndex, or from the end with FindLast and FindLastIndex.
Lambda expression syntax specifies the predicate function, which tests each element. Exists() and Find() are used with similar syntax. Exists() returns a Boolean, not a List.
© 2007-2021 sam allen. see site info on the changelog