VB.Netのお勉強



Dictionaryを利用@VB.Net

ジェネリッククラスであるDictionaryを利用します。

Keyと値の型を指定して、Dictionaryを生成します。
以下では、KeyをInteger、値をStringとして生成しています。

要素の追加は、Addメソッドもしくは、
キーを指定して値を設定のどちらかで行えます。

DictionaryのKeys、Valuesにより、
Key値と値を取得することができます。
以下では、For Eachでそれぞれの値を取り出しています。

また、KeyValuePairによりKeyと値を取得することができます。
以下では、For EachでKeyと値を取り出しています。


'System.Collections.Generic.Dictionary
'KeyはIntegerで、値はString
Dim dict As New System.Collections.Generic.Dictionary(Of Integer, String)

'要素を追加
dict(1) = "AAA"
dict.Add(2, "BBB")

'Keyの取り出し
For Each key As Integer In dict.Keys
    Console.WriteLine(key.ToString)
Next

'値の取り出し
For Each val As String In dict.Values
    Console.WriteLine(val)
Next

'Keyと値の取り出し
For Each keyValue As System.Collections.Generic.KeyValuePair(Of Integer, String) In dict
    Console.WriteLine("{0} : {1}", keyValue.Key, keyValue.Value)
Next




Copyright (C) 2008-2011 VB.Netのお勉強. All Rights Reserved.