Pass in Array to Select Case
this may be a dense question and I'm not finding it to be a dup of this one, but I need some help with understanding if an array can be used in a Select Case statement.
I have a sub routine that I will create a string array dynamically. The XML is also listed, but it could be any of the values listed below. It will be something like this:
Dim offensiveLine() As String = New String() {"center", "right wing", "left wing"}
Dim defensiveLine As String = "defense"
Dim playerInfo = <Player><Name>John</Name><Position val="right wing"/></Player>
What I want to do is see if this p开发者_开发技巧layer is in one of the offensiveLine. So I say:
Dim playerPosition = playerInfo.Position.@val
Select Case playerPosition
Case offensiveLine
'do something
Case defensiveLine
'do something
Case Else
'do nothing
End Select
Here is lies the issue: Case offensiveLine
is invalid. I know I could write out Case "center", "right wing", "left wing"
, but that would defeat the purpose of what I'm trying to do, which is to make a generalized variable that is an array that can be read from in a Case statement. Secondly, I know I can't create a variable like Dim offensiveLine = ""center", "right wing", "left wing""
and pass that in.
Any insight on how I may be able to pass in an array to a Case statement and have each one evaluated?
You may want to consider using an if clause here rather than a switch. Try this logic: if offensiveLine contains playerPosition, then offensive line, etc.
You actually can use a Select
statement:
Dim playerPosition = playerInfo.Position.@val
Select Case True
Case offensiveLine.Contains(playerPosition)
'do something
Case defensiveLine.Contains(playerPosition)
'do something
Case Else
'do something - otherwise you don't need the 'Case Else'
End Select
The trick is the True in the first line of the Select
.
The Select..Case
construct does not work like that. However, it is easy to test if an element exists in an array:
If offensiveLine.Contains(playerPosition) Then
'Do something
ElseIf defensiveLine.Contains(playerPosition) Then
'Do something else
End If
精彩评论