.net 检查字符串是否不等于任何字符串列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16725039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:16:06  来源:igfitidea点击:

Check whether a string is not equal to any of a list of strings

.netvb.net

提问by paulopulus

Is there a way to convert some code like this:

有没有办法像这样转换一些代码:

If someString <> "02" And someString <> "03" And someString <> "06" And someString <> "07" Then
     btnButton.Enabled = False
End If

kinda into something like this (multiple values for one variable)

有点像这样(一个变量有多个值)

If someString <> "02", "03", "06", "07" Then
     btnButton.Enabled = False
End If

回答by Fabian Tamp

Would Containswork?

Contains工作吗?

Dim testAgainst As String() = {"02","03","06","07"}
If Not testAgainst.Contains(someString) Then
    btnButton.Enabled = False
End If

回答by Ry-

You can (ab)use Selectfor this in simple cases:

您可以(ab)Select在简单的情况下用于此:

Select Case someString
    Case "02", "03", "06", "07"
    Case Else
        btnButton.Enabled = False
End Select

Also, a common extension that I use is:

另外,我使用的一个常见扩展是:

<Extension()>
Function [In](Of TItem, TColl)(this As TItem, ParamArray items() As TColl)
    Return Array.IndexOf(items, this) > -1
End Function

So:

所以:

If Not someString.In("02", "03", "06", "07") Then
    btnButton.Enabled = False
End If

回答by Johnno Nolan

Dim invalidvalues As New List(Of String) From { _
    "02", _
    "03,", _
    "04", _
    "07" _
}

If invalidvalues.Contains(x) Then
    btnButton.Enabled = False
End If

回答by Paul Stevens

How about this?

这个怎么样?

Imports System.Text.RegularExpressions    

btnButton.Enabled = Regex.IsMatch(someString, "^0[2367]$")