SortedDictionary<TKey,TValue>.Add(TKey, TValue) 메서드

정의

지정한 키와 값을 가지는 요소를 SortedDictionary<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인 경우

같은 키를 가진 요소가 이미 SortedDictionary<TKey,TValue>에 있는 경우

예제

다음 코드 예제에서는 문자열 키가 있는 빈 SortedDictionary<TKey,TValue> 문자열을 만들고 메서드를 Add 사용하여 일부 요소를 추가합니다. 이 예제에서는 메서드가 Add 중복 키를 추가하려고 할 때 을 throw ArgumentException 하는 것을 보여 줍니다.

이 코드 예제는에 대해 제공 된 큰 예제의 일부는 SortedDictionary<TKey,TValue> 클래스입니다.

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

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

' Add some elements to the dictionary. 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 dictionary.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try

설명

속성을 사용하여 Item[] 에 없는 SortedDictionary<TKey,TValue>키의 값을 설정하여 새 요소를 추가할 수도 있습니다(예 myCollection["myNonexistentKey"] = myValue : Visual Basic의 myCollection("myNonexistantKey") = myValue경우 ). 그러나 지정된 키가 에 SortedDictionary<TKey,TValue>이미 있는 경우 속성을 설정 Item[] 하면 이전 값이 덮어씁니다. 반면 지정된 Add 키를 가진 요소가 이미 있는 경우 메서드는 예외를 throw합니다.

키는 일 수 없지만 null값 형식이 참조 형식 TValue 인 경우 값이 될 수 있습니다.

이 메서드는 O(로그 n) 작업이며 여기서 n 는 입니다 Count.

적용 대상

추가 정보