語言

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 參考型別。

實作

例外狀況

key 是 null。

具有相同鍵的元素已存在 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> 並先將現有元素複製到新陣列,然後再加入新元素。

此方法是對未排序資料的 O(n) 操作,其中 n 為 Count。 若新元素被加入於列表末尾,則稱為 O(log n) 操作。 若插入導致大小調整,則操作為 O(n)。

適用於

另請參閱