[VB.NET]泛型集合

[VB.NET]泛型集合

image

 

Public Class Form1

    Private Sub btn_List_Click(sender As System.Object, e As System.EventArgs) Handles btn_List.Click
        Label1.Text = ""
        Dim list As New List(Of String)
        list.Add(New String("1"))
        list.Add(New String("5"))
        list.Add(New String("3"))
        list.Add("4")
        list.ForEach(AddressOf printlist)
        Label1.Text += vbCrLf
        list.Sort() '排序
        list.ForEach(AddressOf printlist)
    End Sub

    Private Sub printlist(ByVal str As String)
        Label1.Text += str
    End Sub

  
    Private Sub btn_Dictionary_Click(sender As System.Object, e As System.EventArgs) Handles btn_Dictionary.Click
        Label1.Text = ""
        Dim books As New Dictionary(Of String, String)
        books.Add("vb book", 100)
        books.Add("C# book", 200)
        books.Add("C++ book", 300)
        For Each book As KeyValuePair(Of String, String) In books
            Label1.Text += "書名:" & book.Key & "      售價:" & book.Value + vbCrLf
        Next

    End Sub
    
    Private Sub btn_SortedDictionary_Click(sender As System.Object, e As System.EventArgs) Handles btn_SortedDictionary.Click
        Label1.Text = ""
        Dim books As New SortedDictionary(Of String, String)
        books.Add("vb book", 100)
        books.Add("C# book", 200)
        books.Add("C++ book", 300)
        'For Each book As KeyValuePair(Of String, String) In books
        '    Label1.Text += "書名:" & book.Key & "      售價:" & book.Value + vbCrLf
        'Next

        '除了使用KeyValuePair也可使用keys與value 屬性存取
        For Each key As String In books.Keys
            Label1.Text += "書名:" & key & "      售價:" & books(key) + vbCrLf
        Next
    End Sub

 
    Private Sub btn_SortedList_Click(sender As System.Object, e As System.EventArgs) Handles btn_SortedList.Click
        Label1.Text = ""
        Dim books As New SortedList(Of String, String)
        books.Add("vb book", 100)
        books.Add("C# book", 200)
        books.Add("C++ book", 300)
        For Each book As KeyValuePair(Of String, String) In books
            Label1.Text += "書名:" & book.Key & "      售價:" & book.Value + vbCrLf
        Next
    End Sub
End Class

 

若只需要增加一個實質型別用List泛型類別

要用 key value 的增加且不排序 就用Dictionary要排序就用 SortedList

Generic.rar


如有錯誤 歡迎指正