SortedList<TKey,TValue>.Add(TKey, TValue) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将具有指定键和值的元素添加到 .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)。