IndexOf
searches for exact match. To customize the matching criteria, you can use the FindIndex
method:
// Finds first element of the array that contains `inputString`
Array.FindIndex(arr, Function(s) s.Contains(inputString))
// Finds first element of the array that begins with `inputString`
Array.FindIndex(arr, Function(s) s.StartsWith(inputString))
Edit to clarify Function(s)
and lambdas:
Array.FindIndex
takes two arguments, the first of which is an array you want to work on, the latter is a Delegate
representing the predicate to check.
FindIndex
does not have any idea about what kind of element you want. It gives you the flexibility to specify it. You tell it by passing in a function that takes an array element and returns a boolean indicating whether you want it or not.
It essentially calls that function with every element of the array and returns the index of the first element for which that function returns true.
Instead of writing a whole function and passing it using AddressOf MyPredicate
, we can easily use the Function(s) s.Contains(inputString)
. It's equivalent to:
Function MyPredicate(s As String) As Boolean
Return s.Contains(inputString)
End Function
Array.FindIndex(arr, AddressOf MyPredicate)
Of course if we did that, we had to store inputString
somewhere accessible to that method. It's a lot of dirty code. A lambda expression reduces all these hassles.
Edit 2:
I can verify this code prints "1":
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "somu", "arul"}
Console.WriteLine(Array.FindIndex(arr, Function(s) s.Contains("so")))
End Sub
End Module