ListDictionary.Add(Object, Object) Метод

Определение

Добавляет запись с указанными ключом и значением в ListDictionary.

public:
 virtual void Add(System::Object ^ key, System::Object ^ value);
public void Add (object key, object value);
public void Add (object key, object? value);
abstract member Add : obj * obj -> unit
override this.Add : obj * obj -> unit
Public Sub Add (key As Object, value As Object)

Параметры

key
Object

Ключ записи, которую требуется добавить.

value
Object

Добавляемое значение записи. Допускается значение null.

Реализации

Исключения

key имеет значение null.

Запись с таким ключом уже существует в ListDictionary.

Примеры

В следующем примере кода добавляются элементы в и удаляются ListDictionaryиз .

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Specialized;
void PrintKeysAndValues( IDictionary^ myCol )
{
   Console::WriteLine( "   KEY                       VALUE" );
   IEnumerator^ myEnum = myCol->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      DictionaryEntry de = safe_cast<DictionaryEntry>(myEnum->Current);
      Console::WriteLine( "   {0,-25} {1}", de.Key, de.Value );
   }

   Console::WriteLine();
}

int main()
{
   
   // Creates and initializes a new ListDictionary.
   ListDictionary^ myCol = gcnew ListDictionary;
   myCol->Add( "Braeburn Apples", "1.49" );
   myCol->Add( "Fuji Apples", "1.29" );
   myCol->Add( "Gala Apples", "1.49" );
   myCol->Add( "Golden Delicious Apples", "1.29" );
   myCol->Add( "Granny Smith Apples", "0.89" );
   myCol->Add( "Red Delicious Apples", "0.99" );
   
   // Displays the values in the ListDictionary in three different ways.
   Console::WriteLine( "Initial contents of the ListDictionary:" );
   PrintKeysAndValues( myCol );
   
   // Deletes a key.
   myCol->Remove( "Gala Apples" );
   Console::WriteLine( "The collection contains the following elements after removing \"Gala Apples\":" );
   PrintKeysAndValues( myCol );
   
   // Clears the entire collection.
   myCol->Clear();
   Console::WriteLine( "The collection contains the following elements after it is cleared:" );
   PrintKeysAndValues( myCol );
}

/*
This code produces the following output.

Initial contents of the ListDictionary:
   KEY                       VALUE
   Braeburn Apples           1.49
   Fuji Apples               1.29
   Gala Apples               1.49
   Golden Delicious Apples   1.29
   Granny Smith Apples       0.89
   Red Delicious Apples      0.99

The collection contains the following elements after removing "Gala Apples":
   KEY                       VALUE
   Braeburn Apples           1.49
   Fuji Apples               1.29
   Golden Delicious Apples   1.29
   Granny Smith Apples       0.89
   Red Delicious Apples      0.99

The collection contains the following elements after it is cleared:
   KEY                       VALUE

*/
using System;
using System.Collections;
using System.Collections.Specialized;

public class SamplesListDictionary  {

   public static void Main()  {

      // Creates and initializes a new ListDictionary.
      ListDictionary myCol = new ListDictionary();
      myCol.Add( "Braeburn Apples", "1.49" );
      myCol.Add( "Fuji Apples", "1.29" );
      myCol.Add( "Gala Apples", "1.49" );
      myCol.Add( "Golden Delicious Apples", "1.29" );
      myCol.Add( "Granny Smith Apples", "0.89" );
      myCol.Add( "Red Delicious Apples", "0.99" );

      // Displays the values in the ListDictionary in three different ways.
      Console.WriteLine( "Initial contents of the ListDictionary:" );
      PrintKeysAndValues( myCol );

      // Deletes a key.
      myCol.Remove( "Gala Apples" );
      Console.WriteLine( "The collection contains the following elements after removing \"Gala Apples\":" );
      PrintKeysAndValues( myCol );

      // Clears the entire collection.
      myCol.Clear();
      Console.WriteLine( "The collection contains the following elements after it is cleared:" );
      PrintKeysAndValues( myCol );
   }

   public static void PrintKeysAndValues( IDictionary myCol )  {
      Console.WriteLine( "   KEY                       VALUE" );
      foreach ( DictionaryEntry de in myCol )
         Console.WriteLine( "   {0,-25} {1}", de.Key, de.Value );
      Console.WriteLine();
   }
}


/*
This code produces the following output.

Initial contents of the ListDictionary:
   KEY                       VALUE
   Braeburn Apples           1.49
   Fuji Apples               1.29
   Gala Apples               1.49
   Golden Delicious Apples   1.29
   Granny Smith Apples       0.89
   Red Delicious Apples      0.99

The collection contains the following elements after removing "Gala Apples":
   KEY                       VALUE
   Braeburn Apples           1.49
   Fuji Apples               1.29
   Golden Delicious Apples   1.29
   Granny Smith Apples       0.89
   Red Delicious Apples      0.99

The collection contains the following elements after it is cleared:
   KEY                       VALUE

*/
Imports System.Collections
Imports System.Collections.Specialized

Public Class SamplesListDictionary   

   Public Shared Sub Main()

      ' Creates and initializes a new ListDictionary.
      Dim myCol As New ListDictionary()
      myCol.Add("Braeburn Apples", "1.49")
      myCol.Add("Fuji Apples", "1.29")
      myCol.Add("Gala Apples", "1.49")
      myCol.Add("Golden Delicious Apples", "1.29")
      myCol.Add("Granny Smith Apples", "0.89")
      myCol.Add("Red Delicious Apples", "0.99")

      ' Displays the values in the ListDictionary in three different ways.
      Console.WriteLine("Initial contents of the ListDictionary:")
      PrintKeysAndValues(myCol)

      ' Deletes a key.
      myCol.Remove("Gala Apples")
      Console.WriteLine("The collection contains the following elements after removing ""Gala Apples"":")
      PrintKeysAndValues(myCol)

      ' Clears the entire collection.
      myCol.Clear()
      Console.WriteLine("The collection contains the following elements after it is cleared:")
      PrintKeysAndValues(myCol)

   End Sub

   Public Shared Sub PrintKeysAndValues(myCol As IDictionary)

      Console.WriteLine("   KEY                       VALUE")
      Dim de As DictionaryEntry
      For Each de In  myCol
         Console.WriteLine("   {0,-25} {1}", de.Key, de.Value)
      Next de
      Console.WriteLine()

   End Sub

End Class


'This code produces the following output.
'
'Initial contents of the ListDictionary:
'   KEY                       VALUE
'   Braeburn Apples           1.49
'   Fuji Apples               1.29
'   Gala Apples               1.49
'   Golden Delicious Apples   1.29
'   Granny Smith Apples       0.89
'   Red Delicious Apples      0.99
'
'The collection contains the following elements after removing "Gala Apples":
'   KEY                       VALUE
'   Braeburn Apples           1.49
'   Fuji Apples               1.29
'   Golden Delicious Apples   1.29
'   Granny Smith Apples       0.89
'   Red Delicious Apples      0.99
'
'The collection contains the following elements after it is cleared:
'   KEY                       VALUE
'

Комментарии

Объект, не имеющий корреляции между состоянием и значением хэш-кода, обычно не должен использоваться в качестве ключа. Например, объекты String лучше, чем объекты StringBuilder для использования в качестве ключей.

Свойство также можно использовать Item[] для добавления новых элементов, задав значение ключа, не существующего ListDictionaryв ; например, myCollection["myNonexistentKey"] = myValue. Однако если указанный ключ уже существует в ListDictionary, установка Item[] свойства перезаписывает старое значение. В отличие от этого, Add метод не изменяет существующие элементы.

Этот метод является операцией O(n), где n — .Count

Применяется к

См. также раздел