跳至內容

Visual Basic/詞典

來自 Wikibooks,開放世界中的開放書籍

除了集合類提供的功能外,字典類還提供一些功能。字典是一系列鍵值對。與集合不同,只能透過 Microsoft Scripting Runtime 使用字典類,而該執行時的引用需要新增到專案中才能使用該類。

建立字典

  Set Dict = New Dictionary
  Set Dict = CreateObject("Scripting.Dictionary") 'An alternative

將鍵和項新增到字典

  Dict.Add "Key1", "Value1"
  Dict.Add "Key2", "Value2"
  Dict.Add Key:="Key3", Item:="Value3"

透過鍵訪問項

  Value3 = MyDict.Item("Key3")

透過索引訪問項

  Index = 2
  Counter = 1
  For Each Key In Dict.Keys
    If Counter = Index Then
      FoundKey = Key
      FoundValue = Dict.Item(Key)
      Exit For
    End If
    Counter = Counter + 1
  Next

遍歷鍵

  For Each Key In Dict.Keys
    Value = Dict.Item(Key)
  Next

遍歷值

  For Each Value In Dict.Items
    '...
  Next

移除項

  Dict.Remove "Key3"

移除所有項或清空

  Dict.RemoveAll

大小或元素數量

  Dict.Count

測試是否為空

  If Dict.Count = 0 Then
    '...
  End If

更改項的鍵

  Dict.Key("Key1") = "Key1a"

更改項的值

  Dict.Item("Key2") = "Value2a"

測試鍵是否存在

  If Dict.Exists("Key2") Then
    '..
  End If

將字典用作集合

將虛擬值 1 與集合的每個元素關聯。
在新增項時,測試是否存在。
  Set DictSet = New Dictionary
  DictSet.Add "Item1", 1
  'DictSet.Add "Item1", 1 -- error: the item is already there
  If Not DictSet.Exists("Item1") Then
    DictSet.Add "Item1", 1
  End If
  DictSet.Remove "Item1"
華夏公益教科書