Home > Mobile >  collection object displaying only key
collection object displaying only key

Time:04-20

I have created a collection and added some values to it. Now how can I display both key and value for the items.

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

Message box is only displaying key, how can I print the message like: "1 - sunday", "2 - monday"

CodePudding user response:

Here is the equivalent of what you've do so far, using the more modern dictionary collection:

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

I expect that you've transposed the idea of a key and and value and maybe this is what you actually need:

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

Finally, a better version might be this:

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
  • Related