Find an element in Array ( .NET )

Most of us will often need to find an element in an array.  In C or C++, we can do this by using the FOR loops. In .NET 2.0, we have a build-in method, which is very simple and powerful too. It is similar to ArrayList’s Contains method. The following code snippet will show this. 

Private Function MyMethod() as string
  Dim countryCodes() As String
  countryCodes = “IND,CHI,JPN”.Split(“,”.ToCharArray)
  If Array.Exists(countryCodes, AddressOf CountryCodeStartsWith) Then
  Return “Exists”
  Else
  Return “Not Exists”
  End If
End Function

Private Function CountryCodeStartsWith(ByVal countryCode As String) As Boolean
  dim Country as string = “INDIA”
  If Country.startsWith(countryCode) Then
     Return True
  Else
     Return False
  End If
End Function

The Array.Exists has two parameters. The first one is nothing but an array where the element is to searched. The second part of the code , which will be confusing for beginners, is a delegate for the function. At the time of execution the elements in CountryCodes – Our Array – will be passed as a parameter to this delegate. also we can customize this matching function very easily.
Hope this will help you.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s