SortedList.Add(Object, Object) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将具有指定键和值的元素添加到对象 SortedList 。
public:
virtual void Add(System::Object ^ key, System::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 ,并在添加新元素之前将现有元素复制到新数组。
还可以通过设置对象中SortedList不存在的键的值(例如,myCollection["myNonexistentKey"] = myValue)来使用该Item[]属性来添加新元素。 但是,如果指定的键已存在于该属性中 SortedList,则设置该 Item[] 属性将覆盖旧值。 相反,该方法 Add 不会修改现有元素。
对象的元素SortedList根据创建时IComparer指定的特定SortedList实现或键本身提供的实现按IComparable键排序。
键不能 null,但值可以是。
此方法是O(n)未排序数据的操作,其中 n 。Count 如果新元素在列表末尾添加,则它是一个 O(log n) 操作。 如果插入导致调整大小,则操作为 O(n)。