Home »
.Net »
C# Programs
C# program to copy SortedList elements to a one-dimensional Array object (Example of CopyTo() Method)
C# SortedList.CopyTo() Method: Here, we are going to learn how to copy SortedList elements to a one-dimensional Array object in C#.Net?
Submitted by Nidhi, on May 02, 2021
The CopyTo() method of SortedList class is used to copy SortedList elements to a one-dimensional array, starting at the specified index of the array.
Syntax:
void SortedList.CopyTo(Array array, int arrayIndex);
Parameter(s):
- array: Used to copy elements of SortedList.
- arrayIndex: The index in array at which copying begins
Return value:
It does not return any value.
Exception(s):
- System.ArgumentNullException
- System.ArgumentOutOfRangeException
- System.ArgumentException
- System.InvalidCastException
Program:
The source code to copy SortedList elements to a one-dimensional Array object is given below. The given program is compiled and executed successfully.
using System;
using System.Collections;
class SortedListEx
{
//Entry point of Program
static public void Main()
{
//Creation of SortedList object
SortedList list = new SortedList();
//Add elements to SortedList
list.Add(101, "India ");
list.Add(105, "America ");
list.Add(102, "Austrelia");
list.Add(103, "Africa ");
list.Add(104, "Canada ");
Console.WriteLine("SortedList Values:");
foreach (string value in list.Values)
{
Console.WriteLine("\t" + value);
}
//
DictionaryEntry[] arr = new DictionaryEntry[list.Count];
//Here we copy sorted list elements to specified index of array
list.CopyTo(arr, 0);
//Now we print array elements
Console.WriteLine("Array Values:");
for (int index = 0; index < arr.Length; index++)
{
Console.WriteLine("\t"+arr[index].Value);
}
}
}
Output:
SortedList Values:
India
Austrelia
Africa
Canada
America
Array Values:
India
Austrelia
Africa
Canada
America
Press any key to continue . . .
C# SortedList Class Programs »