2010年11月16日 星期二

VB 2008 Dictionary Sample

'Dictionary Sample
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim str1 = ""
        Dim dict1 As New Dictionary(Of Integer, String)

        dict1.Add(0, "優")
        dict1.Add(1, "佳")
        dict1.Add(2, "可")
        dict1.Add(3, "差")

        str1 = str1 & vbNewLine
        'KeyValuePair
        For Each kvp As KeyValuePair(Of Integer, String) In dict1
            str1 = str1 & kvp.Key & Space(3) & kvp.Value & vbNewLine
        Next kvp

        'assign value
        dict1(3) = "劣"

        'ValueCollection
        Dim valueColl As Dictionary(Of Integer, String).ValueCollection = dict1.Values
        str1 = str1 & vbNewLine
        For Each s As String In valueColl
            str1 = str1 & "Value = " & s & vbNewLine
        Next s

        'KeyCollection
        Dim keyColl As Dictionary(Of Integer, String).KeyCollection = dict1.Keys

        str1 = str1 & vbNewLine
        For Each s As String In keyColl
            str1 = str1 & "Key = " & s & vbNewLine
        Next s

        'Query
        str1 = str1 & vbNewLine
        str1 = str1 & dict1(2) & vbNewLine

        'Remove
        str1 = str1 & vbNewLine & "Remove(2)"

        dict1.Remove(2)

        'ContainsKey
        str1 = str1 & vbNewLine
        If Not dict1.ContainsKey(2) Then
            str1 = str1 & "Key ""2"" is not found."
        End If
        MsgBox(str1)
    End Sub
End Class

Learning

沒有留言: