有没有办法在vb.net中的每个循环中循环多个变量?

时间:2011-03-29 14:53:16

标签: vb.net

我想循环遍历两个字符串数组但不起作用。 可能看起来像下面这样:

For Each (s1, s2) As (String, String) In (stringArray1, stringArray2)

我可以使用类似于python元组的东西吗?

4 个答案:

答案 0 :(得分:2)

我认为vb.net不支持这种方式。

如果你有两个IEnumerables,你可以做这样的事情

Using lst1 As IEnumerator(Of X) = List1.GetEnumerator(),
      lst2 As IEnumerator(Of Y) = List2.GetEnumerator()

    While lst1 .MoveNext() AndAlso lst2 .MoveNext() 
        If lst1 .Current.Equals(lst2 .Current) Then
            ''Put here your code.
        End If
    End While
End Using

要获得更好的解释,请查看以下相关链接:Is it possible to iterate over two IEnumerable objects at the same time?

答案 1 :(得分:1)

在.Net 4中,您可以使用Ziptuples

Sub Main()
    Dim arr1() As String = {"a", "b", "c"}
    Dim arr2() As String = {"1", "2", "3"}
    For Each t In TupleSequence(arr1, arr2)
        Console.WriteLine(t.Item1 & "," & t.Item2)
    Next
    Console.ReadLine()
End Sub
Function TupleSequence(Of T1, T2)(
    ByVal seq1 As IEnumerable(Of T1),
    ByVal seq2 As IEnumerable(Of T2)
    ) As IEnumerable(Of Tuple(Of T1, T2))
    Return Enumerable.Zip(seq1, seq2, 
      Function(s1, s2) Tuple.Create(s1, s2)
    )
End Function

不如Python那么好。

答案 2 :(得分:0)

如果它们长度相同,你可以做类似......

dim i as integer = 0
do until i = s1.length
dim s1Value as string = s1(i)
dim s2Value as string = s2(i)
i += 1
loop

答案 3 :(得分:-1)

之前我研究过同样的问题,但在VB.Net中找不到编码的好方法。但我认为没有必要像Python,Tcl等那样做。所以我只使用For-Loop,类似于Jack的答案。这也适用于List。

'List1.Count = List2.Count
For i as Integer = 0 To List1.Count - 1
        'Work on List1.Item(i) and List2.Item(i)
Next
相关问题