VB.NET - Alternative to Array.Contains?

15,055

Solution 1

You will have to rewrite your code, like so...

If (Array.IndexOf(New String() {"ER", "PM", "EM", "OC"}), Session("Position")>-1) Then
        'Some codes
End If

The collection initializer is depends on the compiler, but not the framework being targetted, so this should work.

Edit: fixed wrong method/ condition. I got interupted with a leaky sink as I was working on this, and didn't mean to post it until I'd verified that it works.

http://ideone.com/i84QX

Solution 2

You can achieve this with Exists or Find

If Array.Exists(New String() {"ER", "PM", "EM", "OC"}, AddressOf FindExistance) Then
    'Some codes   
End If



Private Function FindExistance(ByVal s As String) As Boolean
    If String.Equals(s, Session("Position")) Then
        Return True
    Else
        Return False
    End If
End Function
Share:
15,055
kazinix
Author by

kazinix

Updated on June 04, 2022

Comments

  • kazinix
    kazinix almost 2 years

    Before, I use this on .NET Framework 3.5 and it's working fine:

        If (New String() {"ER", "PM", "EM", "OC"}).Contains(Session("Position")) Then
            'Some codes
        End If
    

    Now I am doing a project that runs with .NET 2.0 and the code above is not working, it's giving me this:

    'Contains' is not a member of 'System.Array'.
    

    How can I achieve the codes above (.Contains) without migrating from 2.0 to 3.0? Any alternatives?

    • user1703401
      user1703401 over 12 years
      If Array.IndexOf(New String() { ... }, Session("Position")) >= 0 Then
  • kazinix
    kazinix over 12 years
    I don't understand how the examples on the articles will help me to translate my code to Exists or to Find.
  • kazinix
    kazinix over 12 years
    It's not working Argument not specified for parameter 'match' of 'Public Shared Function Find(Of T)(array() As T, match As System.Predicate(Of T)) As T
  • Koen
    Koen over 12 years
    Appologies for the delay. Sample added.
  • kazinix
    kazinix over 12 years
    The reason why I'm using array literal in a condition is to avoid long codes such as If Session("Position") = "ER" Or Session("Position") = "PM" Or Session("Position") = "EM" ...