Home »
.Net »
C# Programs
C# - SortedList.Add() Method with Example
In this tutorial, we will learn about the C# SortedList.Add() method with its definition, usage, syntax, and example.
By Nidhi Last updated : March 31, 2023
SortedList.Add() Method
The SortedList.Add() is used to adds an element with the specified key and value to a SortedList object.
Syntax
void SortedList.Add(object key, object value);
Parameter(s)
- key: Element's key to be stored.
- value: Element's value to be stored.
Return Value
This method does not return any value.
Exception(s)
- System.ArgumentNullException
- System.ArgumentException
- System.NotSupportedExecption
- System.OutOfMemoryException
- System.InvalidOperationException
C# Example of SortedList.Add() Method
The source code to add elements into a SortedList 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 list1 = new SortedList();
// Creating another object SortedList with initialization
SortedList list2 = new SortedList() {
{ 1, "MP" },
{ 4, "UP" },
{ 3, "AP" },
{ 2, "HP" }
};
//Add elements to first SortedList
list1.Add(1, "India");
list1.Add(5, "America");
list1.Add(2, "Australia");
list1.Add(3, "Africa");
list1.Add(4, "Canada");
Console.WriteLine("List1:");
foreach (DictionaryEntry val in list1)
{
Console.WriteLine("\t{0} : {1}",
val.Key, val.Value);
}
Console.WriteLine();
Console.WriteLine("List2:");
foreach (DictionaryEntry val in list2)
{
Console.WriteLine("\t{0} : {1}",
val.Key, val.Value);
}
}
}
Output
List1:
1 : India
2 : Australia
3 : Africa
4 : Canada
5 : America
List2:
1 : MP
2 : HP
3 : AP
4 : UP
Press any key to continue . . .
C# SortedList Class Programs »