1

I would like to loop over two string arrays but does not work. Would probably look something like the following:

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

Is there something similar to python tuples that I could use?

4 Answers 4

3

I think that vb.net don't support this in this way.

If you have two IEnumerables, you can do something like this

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

For a better explanation, check this related link: Is it possible to iterate over two IEnumerable objects at the same time?

Sign up to request clarification or add additional context in comments.

1 Comment

I think you've copied an answer from the link. But the linked question was slightly different: it was seeking equal entries. I think you should remove the If If lst1 .Current.Equals(lst2 .Current) Then
1

In .Net 4 you could use Zip and tuples.

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

Not as nice as the Python though.

Comments

0

If they are the same length you could do something like...

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

Comments

-1

I have studied the same question before, but found no beautiful way for coding in VB.Net. But I think it is not necessary do the same as in Python, Tcl, etc. So I just use a For-Loop, similar to Jack's answer. This also works for List.

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

1 Comment

My guess would be that this isn`t to efficient, since in classical list each Item request would walk from list start to i element to access it. Maybe .net is built for this command to be more efficient, but this probably would be a bad practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.