Open In App

C# | Remove all elements from a SortedList

SortedList class is a collection of (key, value) pairs which are sorted according to keys. Those pairs can be accessible by key and as well as by index(zero-based indexing). This comes under System.Collections namespace. SortedList.Clear method is used to remove all the elements from a SortedList object.

Properties:



Syntax :

public virtual void Clear ();

Exceptions:



Example:




// C# code to remove all
// elements from a SortedList
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating an SortedList
        SortedList mySortedList = new SortedList();
  
        // Adding elements to SortedList
        mySortedList.Add("1", "1st");
        mySortedList.Add("2", "2nd");
        mySortedList.Add("3", "3rd");
        mySortedList.Add("4", "4th");
        mySortedList.Add("5", "5th");
        mySortedList.Add("6", "6th");
        mySortedList.Add("7", "7th");
  
        // Displaying number of elements
        Console.WriteLine("Number of elements in SortedList is : " 
                                            + mySortedList.Count);
  
        // Displaying capacity
        Console.WriteLine("capacity of SortedList is : " 
                               + mySortedList.Capacity);
  
        // Removing all elements from SortedList
        mySortedList.Clear();
  
        // Displaying number of elements
        Console.WriteLine("Number of elements in SortedList is : "
                                            + mySortedList.Count);
  
        // Displaying capacity
        Console.WriteLine("capacity of SortedList is : " 
                               + mySortedList.Capacity);
    }
}

Output:
Number of elements in SortedList is : 7
capacity of SortedList is : 16
Number of elements in SortedList is : 0
capacity of SortedList is : 16

Note:

Reference:


Article Tags :
C#