C# | Insert a new entry in OrderedDictionary with specified key and value
OrderedDictionary.Insert(Int32, Object, Object) Method is used to inserts a new entry into the OrderedDictionary collection with the specified key and value at the specified index.
Syntax:
public void Insert (int index, object key, object value);
Parameters:
index: It is the zero-based index of type System.Int32 at which the element should be inserted.
key: It is the key of the entry to add.
value: It is the value of the entry to add. The value can be null.
Exceptions:
- ArgumentOutOfRangeException: If the index is out of range.
- NotSupportedException: If the collection is read-only.
Below programs illustrate the use of above-discussed method:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
OrderedDictionary myDict = new OrderedDictionary();
myDict.Add( "key1" , "value1" );
myDict.Add( "key2" , "value2" );
myDict.Add( "key3" , "value3" );
myDict.Add( "key4" , "value4" );
myDict.Add( "key5" , "value5" );
Console.WriteLine( "Before Updation: " );
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " --> " + de.Value);
myDict.Insert(5, "key6" , "value6" );
Console.WriteLine( "\nAfter Updation: " );
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " --> " + de.Value);
}
}
|
Output:
Before Updation:
key1 --> value1
key2 --> value2
key3 --> value3
key4 --> value4
key5 --> value5
After Updation:
key1 --> value1
key2 --> value2
key3 --> value3
key4 --> value4
key5 --> value5
key6 --> value6
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
OrderedDictionary myDict = new OrderedDictionary();
myDict.Add( "1" , "C" );
myDict.Add( "2" , "C++" );
myDict.Add( "3" , "Java" );
myDict.Add( "4" , "Python" );
myDict.Add( "5" , "C#" );
Console.WriteLine( "Before Updation: " );
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " --> " + de.Value);
myDict.Insert(6, "6" , "HTML" );
Console.WriteLine( "\nAfter Updation: " );
foreach (DictionaryEntry de in myDict)
Console.WriteLine(de.Key + " --> " + de.Value);
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: index
Note:
- The key and value parameters will be appended to the end of the collection if the index parameter is equal to the number of entries in the OrderedDictionary collection.
- Entries that follow the insertion point move down to accommodate the new entry and the indexes of the moved entries are also updated.
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...