SortedList.Add(Object, Object) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將具有指定索引鍵和值的專案加入至 SortedList 物件。
public:
virtual void Add(System::Object ^ key, System::Object ^ value);
public virtual void Add(object key, object value);
public virtual void Add(object key, object? value);
abstract member Add : obj * obj -> unit
override this.Add : obj * obj -> unit
Public Overridable Sub Add (key As Object, value As Object)
參數
- key
- Object
元素的關鍵是要添加的。
- value
- Object
要加入元素的價值。 其值可以是 null。
實作
例外狀況
key 是 null。
可用記憶體不足以將該元素加入 SortedList。
比較器會拋出例外。
範例
以下程式碼範例說明如何將元素加入物件。SortedList
using System;
using System.Collections;
public class SamplesSortedList {
public static void Main() {
// Creates and initializes a new SortedList.
SortedList mySL = new SortedList();
mySL.Add( "one", "The" );
mySL.Add( "two", "quick" );
mySL.Add( "three", "brown" );
mySL.Add( "four", "fox" );
// Displays the SortedList.
Console.WriteLine( "The SortedList contains the following:" );
PrintKeysAndValues( mySL );
}
public static void PrintKeysAndValues( SortedList myList ) {
Console.WriteLine( "\t-KEY-\t-VALUE-" );
for ( int i = 0; i < myList.Count; i++ ) {
Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) );
}
Console.WriteLine();
}
}
/*
This code produces the following output.
The SortedList contains the following:
-KEY- -VALUE-
four: fox
one: The
three: brown
two: quick
*/
Imports System.Collections
Public Class SamplesSortedList
Public Shared Sub Main()
' Creates and initializes a new SortedList.
Dim mySL As New SortedList()
mySL.Add("one", "The")
mySL.Add("two", "quick")
mySL.Add("three", "brown")
mySL.Add("four", "fox")
' Displays the SortedList.
Console.WriteLine("The SortedList contains the following:")
PrintKeysAndValues(mySL)
End Sub
Public Shared Sub PrintKeysAndValues(myList As SortedList)
Console.WriteLine(ControlChars.Tab & "-KEY-" & ControlChars.Tab & _
"-VALUE-")
Dim i As Integer
For i = 0 To myList.Count - 1
Console.WriteLine(ControlChars.Tab & "{0}:" & ControlChars.Tab & _
"{1}", myList.GetKey(i), myList.GetByIndex(i))
Next i
Console.WriteLine()
End Sub
End Class
' This code produces the following output.
'
' The SortedList contains the following:
' -KEY- -VALUE-
' four: fox
' one: The
' three: brown
' two: quick
備註
插入點是根據物件創建時 SortedList 明確或預設選擇的比較器來決定的。
若 Count 已經等 Capacity於 ,則透過自動重新配置內部陣列來增加物件容量 SortedList ,且在新增元素加入前,已存在元素會先複製到新陣列。
你也可以利用這個 Item[] 特性來新增元素,方法是設定物件中不存在 SortedList 的鍵值(例如 myCollection["myNonexistentKey"] = myValue)。 然而,如果指定的鍵已經存在 SortedList於 中,設定屬性 Item[] 會覆蓋舊值。 相較之下,該 Add 方法不會修改現有元素。
SortedList 物件的元素會根據建立 IComparer 時指定的特定 SortedList 實作,或根據索引鍵本身所提供的 IComparable 實作,依索引鍵本身所指定的特定 SortedList 實作來排序。
索引鍵不能 null,但值可以是 。
此方法是一種 O(n) 處理未排序資料的操作,其中 n 為 Count。 若新元素被加入於清單末尾,則稱為 O(log n) 操作。 若插入導致大小調整,則操作為 O(n)。