我正在尝试编写代码以通过MsgBox()显示来自两个数组的数据。我有下面的代码,但是当然不起作用:
Dim numbers() As Integer = {1, 4, 7}
Dim letters() As String = {"a", "b", "c"}
' Iterate through the list by using nested loops.
For Each number As Integer In numbers and For Each letter As String In letters
MsgBox(number.ToString & letter & " ")
Next
我需要怎么做才能获得看起来像这样的输出? :
1a
4b
7c
答案 0 :(得分:2)
您需要一个使用索引而不是For
循环的For Each
循环:
Dim numbers() As Integer = {1, 4, 7}
Dim letters() As String = {"a", "b", "c"}
For i As Integer = 0 To numbers.Length - 1
MsgBox(numbers(i) & letters(i))
Next
您也可以使用Zip() linq operator:
For Each output As String In numbers.Zip(letters, Function(n, l) n & l)
MsgBox(output)
Next
答案 1 :(得分:0)
您可能会从字典中受益。不知道您要如何完成任意组合两个数组的操作,但是类似这样的方法可能会更好:
Dim Dict As New Dictionary(Of Integer, String) From {{1, "a"}, {4, "b"}, {7, "c"}}
For Each Item In Dict
MsgBox(Item.Key & Item.Value)
Next
这将允许您使用Linq根据ID(整数)查找项目,例如:
Dict.Where(Function(x)x.Key = 1).SingleOrDefault并获取键/值对。