Dictionaryの使い方

カテゴリ: VB.NET
投稿日時:2008/12/26 17:09:02
VB.NETでDictionaryは、以下のように使います。


Dim dict As New Dictionary(Of String, String)   'キーと値の型を引数で指定する

'要素を追加する
dict.Add("c", "cccc")
dict.Add("a", "aaaa")
dict.Add("b", "bbbb")

'キーから値を取得する
MessageBox.Show(dict("c"))

'特定のキーが存在するか確認する
If dict.ContainsKey("a") Then
    MessageBox.Show("aは存在します。")
End If

'特定の値が存在するか確認する
If dict.ContainsValue("bbbb") Then
    MessageBox.Show("bbbbは存在します。")
End If

'ループ処理する
For Each itm As KeyValuePair(Of String, String) In dict
    MessageBox.Show(itm.Key & "=" & itm.Value)
Next

ソートが必要な場合は、SortedDictionaryを使います。キーでソートされます。
Dim sd As New SortedDictionary(Of String, String)
'要素を追加する
sd.Add("c", "cccc")
sd.Add("a", "aaaa")
sd.Add("b", "bbbb")

'ループ処理する
For Each itm As KeyValuePair(Of String, String) In sd
    MessageBox.Show(itm.Key & "=" & itm.Value)
Next
このエントリーをはてなブックマークに追加

スポンサード リンク