Dictionary.Add メソッド
アセンブリ: mscorlib (mscorlib.dll 内)

Dim instance As Dictionary(Of TKey, TValue) Dim key As TKey Dim value As TValue instance.Add(key, value)


Item プロパティを使用すると、Dictionary 内に存在しないキーの値を設定することで、新しい要素を追加することもできます (例 : myCollection[myKey] = myValue) (Visual Basic では myCollection(myKey) = myValue)。ただし、指定したキーが Dictionary 内に既に存在する場合、Item プロパティを設定すると既存の値が上書きされます。一方、Add メソッドは、指定したキーを持つ値が既に存在する場合、例外をスローします。
Count プロパティ値が既に容量に等しい場合には、内部配列を自動的に再割り当てすることにより Dictionary の容量が増加し、新しい要素を追加する前に既存の要素は新しい配列にコピーされます。
キーを null 参照 (Visual Basic では Nothing) にすることはできませんが、TValue が参照型である場合、値を null にすることはできます。
Count が容量より小さい場合、このメソッドは O(1) 操作に近くなります。新しい要素を格納するために容量を増やす必要がある場合、このメソッドは O(n) 操作になります。ここで、n は Count です。

文字列キーを含む文字列の空の Dictionary を作成し、Add メソッドを使用していくつかの要素を追加するコード例を次に示します。この例では、重複するキーを追加しようとすると、Add メソッドが ArgumentException をスローすることを示します。
このコード例は、Dictionary クラスのトピックで取り上げているコード例の一部分です。
' Create a new dictionary of strings, with string keys. ' Dim openWith As New Dictionary(Of String, String) ' Add some elements to the dictionary. There are no ' duplicate keys, but some of the values are duplicates. openWith.Add("txt", "notepad.exe") openWith.Add("bmp", "paint.exe") openWith.Add("dib", "paint.exe") openWith.Add("rtf", "wordpad.exe") ' The Add method throws an exception if the new key is ' already in the dictionary. Try openWith.Add("txt", "winword.exe") Catch Console.WriteLine("An element with Key = ""txt"" already exists.") End Try
// Create a new dictionary of strings, with string keys. // Dictionary<string, string> openWith = new Dictionary<string, string>(); // Add some elements to the dictionary. There are no // duplicate keys, but some of the values are duplicates. openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); // The Add method throws an exception if the new key is // already in the dictionary. try { openWith.Add("txt", "winword.exe"); } catch (ArgumentException) { Console.WriteLine("An element with Key = \"txt\" already exists."); }

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Weblioに収録されているすべての辞書からDictionary.Add メソッドを検索する場合は、下記のリンクをクリックしてください。

- Dictionary.Add メソッドのページへのリンク