C# program to add elements into a SortedList (Example of Add() Method)

C# SortedList.Add() Method: Here, we are going to learn how to add elements into a SortedList in C# programming language? Submitted by Nidhi, on April 26, 2021

The Add() method of SortedList class 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

Program:

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 »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.