ListDictionary.Add Method (Object, Object)
Adds an entry with the specified key and value into the ListDictionary.
Assembly: System (in System.dll)
Parameters
- key
-
Type:
System.Object
The key of the entry to add.
- value
-
Type:
System.Object
The value of the entry to add. The value can be null.
Implements
IDictionary.Add(Object, Object)| Exception | Condition |
|---|---|
| ArgumentNullException | key is null. |
| ArgumentException | An entry with the same key already exists in the ListDictionary. |
An object that has no correlation between its state and its hash code value should typically not be used as the key. For example, String objects are better than StringBuilder objects for use as keys.
You can also use the Item property to add new elements by setting the value of a key that does not exist in the ListDictionary; for example, myCollection["myNonexistentKey"] = myValue. However, if the specified key already exists in the ListDictionary, setting the Item property overwrites the old value. In contrast, the Add method does not modify existing elements.
This method is an O(n) operation, where n is Count.
The following code example adds to and removes elements from a ListDictionary.
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( "Plums" ); Console.WriteLine( "The collection contains the following elements after removing \"Plums\":" ); 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 "Plums": 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 it is cleared: KEY VALUE */
Available since 10
.NET Framework
Available since 1.1