Home »
.Net »
C# Programs
C# - SortedList.CopyTo() Method with Example
In this tutorial, we will learn about the C# SortedList.CopyTo() method with its definition, usage, syntax, and example.
By Nidhi Last updated : March 31, 2023
SortedList.CopyTo() Method
The SortedList.CopyTo() method 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
C# Example of SortedList.CopyTo() Method
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 »