【问题标题】:Is there any IN Operator in VB.net functions like the one in SQLVB.net 函数中是否有任何 IN 运算符,如 SQL 中的函数
【发布时间】:2012-11-22 13:19:04
【问题描述】:

有没有类似的函数或运算符:

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

代替:

    If RoleName = "Val1" Or RoleName = "Val2" Or RoleName = "Val2" Then
        'Go
    End If

【问题讨论】:

    标签: .net vb.net operators


    【解决方案1】:

    尝试使用数组,然后您可以使用 Contains 扩展:

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

    或者没有声明行:

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

    来自 OP,如果 Contains 扩展不可用,您可以试试这个:

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

    【讨论】:

    • 感谢您的回答,但它正在抛出:'contains' 不是 'system.array' 的成员,我找到了解决方案,请更新您的答案:If (Array.IndexOf(New String() {"Val1", "Val2", "Val3"}, RoleName) > -1) Then
    • @Ala 那么您的项目 - 引用列表中可能没有对 System.Linq 的引用。
    • @Ala:也许你错过了文件顶部的导入语句:Imports System.Linq?
    • @Meta-Knight,是的,完全使用System.Linq 解决了错误'contains' is not a member of 'system.array'
    【解决方案2】:

    您可以使用如 LarsTech 所示的 Contains,但添加 In 扩展方法也很容易:

    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
    

    你可以这样使用它:

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

    【讨论】:

      【解决方案3】:

      您也可以使用Select..Case 声明:

      Select Case RoleName 
          Case "Val1", "Val2", "Val3"
              ' Whatever
      End Select
      

      【讨论】:

      • +1 以提高可读性,即使与其他答案相比有点无聊:)
      猜你喜欢
      • 2014-08-20
      • 2011-04-03
      • 2012-12-15
      • 1970-01-01
      • 2018-03-13
      • 2016-07-21
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      相关资源
      最近更新 更多