我已经创建了一个集合并添加了一些值。现在我该如何显示项的键和值呢?
Public Class Form1
Dim CollDay As New Microsoft.VisualBasic.Collection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CollDay.Add(1, "sunday")
CollDay.Add(2, "monday")
CollDay.Add(3, "tuesday")
CollDay.Add(4, "wednesday")
For Each CollDay_ In CollDay
MessageBox.Show(CollDay_)
Next
End Sub
End Class
消息框只显示密钥,我怎么打印这样的消息:&;1 - sunday&;, &;2 - monday&;
下面是您到目前为止所做的等效操作,使用更现代的字典集合:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dictionary As New Dictionary(Of String, Integer)
dictionary.Add("sunday", 1)
dictionary.Add("monday", 2)
dictionary.Add("tuesday", 3)
dictionary.Add("wednesday", 4)
For Each item In dictionary
MessageBox.Show(String.Format("{0} - {1}", item.Value, item.Key))
Next
End Sub
我希望你已经调换了键和值的概念,也许这是你真正需要的:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dictionary As New Dictionary(Of Integer, String)
dictionary.Add(1, "sunday")
dictionary.Add(2, "monday")
dictionary.Add(3, "tuesday")
dictionary.Add(4, "wednesday")
For Each item In dictionary
MessageBox.Show(String.Format("{0} - {1}", item.Key, item.Value))
Next
End Sub
最后,一个更好的版本可能是:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim list As New List(Of String)
list.Add("sunday")
list.Add("monday")
list.Add("tuesday")
list.Add("wednesday")
For i = 0 To list.Count - 1
MessageBox.Show(String.Format("{0} - {1}", i + 1, list(i)))
Next
End Sub