Reputation: 124
I am trying to find a better way to write this code but I can't figure out how to make this cleaner. In other languages I have used in the past I am able to increment the variables with a loop instead of having to apply the same code to several variables. I suppose I am looking for something like this where the variable name itself is being changed or created using the loop:
Dim IP0 As String = ""
While IP0 < 5
IP0 = IP0.Remove(index).Trim
index = IP2.IndexOf(" "c)
IP0 = IP0 + 1
End While
In the above example, I would like the "+1" to actually add to the variable itself. So "IP0" would become "IP1", then "IP2" and so on. This does not compile obviously, is there a way to do this is VB.net? Here are a couple snippets of my current project that I would like to apply this logic to:
Dim IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9 As String
IP1 = IP1.Remove(index).Trim
index = IP2.IndexOf(" "c)
IP2 = IP2.Remove(index).Trim
index = IP3.IndexOf(" "c)
IP3 = IP3.Remove(index).Trim
index = IP4.IndexOf(" "c)
IP4 = IP4.Remove(index).Trim
index = IP5.IndexOf(" "c)
IP5 = IP5.Remove(index).Trim
index = IP6.IndexOf(" "c)
IP6 = IP6.Remove(index).Trim
index = IP7.IndexOf(" "c)
IP7 = IP7.Remove(index).Trim
index = IP8.IndexOf(" "c)
IP8 = IP8.Remove(index).Trim
index = IP9.IndexOf(" "c)
IP9 = IP9.Remove(index).Trim
Using writer As StreamWriter = New StreamWriter("C:\tempFiles\bigBatch.bat")
writer.Write(
"ping -a " & IP1 & " -n 1 > c:\tempFiles\IP1.txt" & vbNewLine &
"ping -a " & IP2 & " -n 1 > c:\tempFiles\IP2.txt" & vbNewLine &
"ping -a " & IP3 & " -n 1 > c:\tempFiles\IP3.txt" & vbNewLine &
"ping -a " & IP4 & " -n 1 > c:\tempFiles\IP4.txt" & vbNewLine &
"ping -a " & IP5 & " -n 1 > c:\tempFiles\IP5.txt" & vbNewLine &
"ping -a " & IP6 & " -n 1 > c:\tempFiles\IP6.txt" & vbNewLine &
"ping -a " & IP7 & " -n 1 > c:\tempFiles\IP7.txt" & vbNewLine &
"ping -a " & IP8 & " -n 1 > c:\tempFiles\IP8.txt" & vbNewLine &
"ping -a " & IP9 & " -n 1 > c:\tempFiles\IP9.txt" & vbNewLine)
End Using
Dim IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9 As String
IP1 = thisArray(3).Trim
IP2 = thisArray(4).Trim
IP3 = thisArray(5).Trim
IP4 = thisArray(6).Trim
IP5 = thisArray(7).Trim
IP6 = thisArray(8).Trim
IP7 = thisArray(9).Trim
IP8 = thisArray(10).Trim
IP9 = thisArray(11).Trim
Upvotes: 0
Views: 987
Reputation: 460158
Just store your similar variables in a collection like String()
or List(Of String)
Dim ipList As New List(Of String) From {"IP1", "IP2", "IP3", "IP4", "IP5", "IP6", "IP7", "IP8", "IP9"}
For i As Int32 = 0 To ipList.Count - 1
Dim ip = ipList(i)
Dim indexOfSpace = ip.IndexOf(" "c)
If indexOfSpace >= 0 Then ipList(i) = ip.Remove(indexOfSpace)
Next
Upvotes: 4