SortedList<TKey,TValue>.Add(TKey, TValue) メソッド

定義

指定したキーと値を持つ要素を SortedList<TKey,TValue>に追加します。

public:
 virtual void Add(TKey key, TValue value);
public void Add(TKey key, TValue value);
abstract member Add : 'Key * 'Value -> unit
override this.Add : 'Key * 'Value -> unit
Public Sub Add (key As TKey, value As TValue)

パラメーター

key
TKey

追加する要素のキー。

value
TValue

追加する要素の値。 値は参照型に null できます。

実装

例外

keynullです。

同じキーを持つ要素が既に SortedList<TKey,TValue>に存在します。

次のコード例では、文字列キーを持つ文字列の空の SortedList<TKey,TValue> を作成し、 Add メソッドを使用していくつかの要素を追加します。 この例では、重複するキーを追加しようとしたときに、 Add メソッドが ArgumentException をスローすることを示します。

このコード例は、 SortedList<TKey,TValue> クラスに提供されるより大きな例の一部です。

// Create a new sorted list of strings, with string
// keys.
SortedList<string, string> openWith =
    new SortedList<string, string>();

// Add some elements to the list. 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 list.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new sorted list of strings, with string 
' keys. 
Dim openWith As New SortedList(Of String, String)

' Add some elements to the list. 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 list.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
// Create a new sorted list of strings, with string
// keys.
let openWith = SortedList<string, string>()

// Add some elements to the list. 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 list.
try
    openWith.Add("txt", "winword.exe");
with
    | :? ArgumentException ->
        printfn "An element with Key = \"txt\" already exists."

注釈

キーを nullすることはできませんが、並べ替えられたリストの値の型が参照型である場合、 TValue値を指定できます。

Item[] プロパティを使用して、SortedList<TKey,TValue>に存在しないキーの値 (myCollection["myNonexistentKey"] = myValueなど) を設定して、新しい要素を追加することもできます。 ただし、指定したキーが既に SortedList<TKey,TValue>に存在する場合は、 Item[] プロパティを設定すると、古い値が上書きされます。 これに対し、 Add メソッドは既存の要素を変更しません。

Countが既にCapacity等しい場合、内部配列を自動的に再割り当てすることでSortedList<TKey,TValue>の容量が増え、新しい要素が追加される前に既存の要素が新しい配列にコピーされます。

このメソッドは、nCountされる、並べ替えられていないデータに対する O(n) 操作です。 リストの末尾に新しい要素が追加された場合は、O (ログ n) 操作です。 挿入によってサイズが変更された場合、操作は O(n) になります。

適用対象

こちらもご覧ください