C# | Copy OrderedDictionary elements to Array instance at the specified index
OrderedDictionary.CopyTo(Array, Int32) method is used to copy the OrderedDictionary elements to a one-dimensional Array object at the specified index.
Syntax:
public void CopyTo (Array array, int index);
Parameters:
array: It is the one-dimensional Array which is the destination of the DictionaryEntry objects copied from OrderedDictionary. The Array must have zero-based indexing.
index: it is the zero-based index in array at which copying begins.
Note: OrderedDictionary.CopyTo(Array, Int32) method doesn’t provide any guarantee to maintain the order of the elements in the OrderedDictionary collection.
Below programs illustrate the use of the 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" );
DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];
myDict.CopyTo(myArr, 0);
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine(myArr[i].Key + "-->"
+ myArr[i].Value);
}
}
}
|
Output:
key3-->value3
key4-->value4
key5-->value5
key2-->value2
key1-->value1
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
OrderedDictionary myDict = new OrderedDictionary();
myDict.Add( "C" , "1" );
myDict.Add( "C++" , "2" );
myDict.Add( "Java" , "3" );
myDict.Add( "C#" , "4" );
DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];
myDict.CopyTo(myArr, -2);
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine(myArr[i].Key + "-->"
+ myArr[i].Value);
}
}
}
|
Runtime Error:
Unhandled Exception:
System.ArgumentOutOfRangeException: Non-negative number required.
Parameter name: arrayIndex
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...