tags:

views:

584

answers:

1

Hai i used searching the array code for index = Array.IndexOf(_arrayName, "Text"). I give full word This working properly. but give some character this is not working . for example

dim arr() as string ={"ravi","somu","arul"}

here i give "somu" that code return 1. but i give "so" that code return -1. but i want Like search. this is passible or not.

+5  A: 

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
Mehrdad Afshari
hai what is this Function(s).
somu
Function(s) declares a lambda (inline function). Essentialy `Function(s) s.Contains(inputString)` means a function that gets `s` and returns `s.Contains(inputString)`. Instead of cluttering up the code and declaring a big function, you just write it inline and pass it to the method.
Mehrdad Afshari
ok sir i understood.but i pass "so" that function return 0i want 1 because somu include "So" okay . thanks you
somu