Is there any IN Operator in VB.net functions like the one in SQL

26,803

Solution 1

Try using an array and then you can use the Contains extension:

Dim s() As String = {"Val1", "Val2", "Val3"}
If s.Contains(RoleName) Then
  'Go      
End If

Or without the declaration line:

If New String() {"Val1", "Val2", "Val3"}.Contains(RoleName) Then
  'Go
End If

From the OP, if the Contains extension is not available, you can try this:

If Array.IndexOf(New String() {"Val1", "Val2", "Val3"}, RoleName) > -1 Then
  'Go
End If

Solution 2

You can use Contains as shown by LarsTech, but it's also very easy to add an In extension method:

Public Module Extensions

    <Extension()> _
    Public Function [In](Of T)(value As T, ParamArray collectionValues As T()) As Boolean
        Return collectionValues.Contains(value)
    End Function

End Module

You can use it like this:

If RoleName.In("Val1", "Val2", "Val3") Then
    'Go
End If

Solution 3

You could also use a Select..Case statement:

Select Case RoleName 
    Case "Val1", "Val2", "Val3"
        ' Whatever
End Select
Share:
26,803
Alaa
Author by

Alaa

Software team lead, Microsoft Certified Professional Developer, MSc. IT (Semantic Computer Vision). Key Skills: Project Management, Enterprise SaaS Development, Quality Assurance, Business Analysis, .NET development, Relational and Graph Databases, Content Management Systems, Knowledge Graphs, Artificial Intelligence, Computer Vision, Machine Learning, and Semantic technologies.

Updated on November 23, 2020

Comments

  • Alaa
    Alaa over 3 years

    Is there any function or operator like:

            If RoleName in ( "Val1",  "Val2" ,"Val2" ) Then
            'Go
        End If
    

    Instead of:

        If RoleName = "Val1" Or RoleName = "Val2" Or RoleName = "Val2" Then
            'Go
        End If
    
  • Alaa
    Alaa over 11 years
    Thanks for your answer, but it's throwing : 'contains' is not a member of 'system.array', I have found a solution, please update your answer: If (Array.IndexOf(New String() {"Val1", "Val2", "Val3"}, RoleName) > -1) Then
  • LarsTech
    LarsTech over 11 years
    @Ala Then you probably don't have a reference to System.Linq in your Project - References list.
  • tsuo euoy
    tsuo euoy over 11 years
    @Ala: Maybe you're missing the imports statement at the top of the file: Imports System.Linq?
  • Alaa
    Alaa over 11 years
    @Meta-Knight, Yes, Exactly using System.Linq has solved the error 'contains' is not a member of 'system.array'.
  • MarkJ
    MarkJ over 11 years
    +1 for readability, even if it's a bit boring compared to the other answers :)