How do you test multiple values for equality in one line? Basically I want to do
if (val1 == val2 == val3 == ... valN)
but in VB.Net.
If val1 = valN AndAlso val2 = valN AndAlso ... Then
End If
This can get cumbersome when testing more than a few values.
If you have a lot of values to test and do this very often, you could write you a helper like this:
Public Function AllTheSame(ByVal ParamArray values() As Object) As Boolean
For index As Integer = 1 To values.Length - 1
If values(0) <> values(index) Then Return False
Next
Return True
End Function
<Fact()> Public Sub testAllTheSame()
Assert.True(AllTheSame("Test"))
Assert.True(AllTheSame("Test", "Test"))
Assert.True(AllTheSame("Test", "Test", "Test"))
Assert.True(AllTheSame(1234))
Assert.True(AllTheSame(1234, 1234, 1234))
Assert.False(AllTheSame("Test", "Test2"))
Assert.False(AllTheSame("Test", "Test", "Test3"))
Assert.False(AllTheSame(1234, 1234, 987))
End Sub
There is no way to chain them together like that. You need to break it up into pair'd comparisions linked by AndAlso
if val1 = val2 AndAlso val2 = val3 AndAlso val1 = val3 Then
来源:https://stackoverflow.com/questions/686485/vb-net-test-multiple-values-for-equality