Array.Find FunctionUse the Array.Find and Array.FindAll Functions to search arrays with Predicates.
This page was last reviewed on Apr 8, 2022.
Array.Find. The VB.NET Array.Find Function is available for all arrays. It searches an array. It applies a Predicate method we specify.
Predicate details. The Predicate we pass to Array.Find indicates whether an element matches or not. It returns a Boolean. We demonstrate Array.Find.
Func, Action, Predicate
An example. First, we use Array.Find with two arguments. The first argument is the array we are searching. And the second is the Predicate definition.
Lambda We use the lambda expression syntax to specify the predicates. We handle String elements.
StartsWith We use the StartsWith Function to test prefixes. We use the Length property to access character counts.
StartsWith, EndsWith
String Length
FindAll We also apply the FindAll Function. This is similar to Find, but it returns an array of all the elements found.
Info Find returns only one element. If no matches are found, Nothing is returned.
Module Module1 Sub Main() ' Input array. Dim arr() As String = {"cat", "dog", "carrot", "bird"} ' Find element starting with "car". Dim value1 As String = Array.Find(arr, Function(x) (x.StartsWith("car"))) Console.WriteLine(value1) ' Find element of length 3. Dim value2 As String = Array.Find(arr, Function(x) (x.Length = 3)) Console.WriteLine(value2) ' Find all elements of length 4 or less. Dim arr2() As String = Array.FindAll(arr, Function(x) (x.Length <= 4)) Console.WriteLine(String.Join(",", arr2)) End Sub End Module
carrot cat cat,dog,bird
Notes, lambdas. We use the Function keyword to specify a lambda. The first part is the argument to the Function, and the second is the expression that the Function evaluates and returns.
Summary. Arrays can be searched with loops. This often results in more complex code—we must manage arrays, elements and indexes. With Find and FindAll, we eliminate these forms of complexity.
For Each, For
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 8, 2022 (edit link).
© 2007-2023 Sam Allen.