C# | Get the number of elements contained in SortedList

SortedList.Count Property is used to get the number of elements contained in a SortedList object.

Syntax:

public virtual int Count { get; }

Property Value: The number of elements contained in the SortedList object.

Below programs illustrate the use of above discussed method:

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to count the number
// of elements in SortedList
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating object of SortedList
        // fslist is the SortedList object
        SortedList fslist = new SortedList();
  
        // Count property is used to get the
        // number of key/value pairs in fslist
        // It will give 0 as no pairs are present
        Console.WriteLine(fslist.Count);
    }
}

chevron_right


Output:

0

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to count the number
// of elements in SortedList
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating object of SortedList
        // fslist is the SortedList object
        SortedList fslist = new SortedList();
  
        // Count property is used to get the
        // number of key/value pairs in fslist
        // It will give 0 as no pairs are present
        Console.WriteLine(fslist.Count);
  
        // Adding key/value pairs in fslist
        fslist.Add("1", "GFG");
        fslist.Add("2", "Geeks");
        fslist.Add("3", "for");
        fslist.Add("4", "Geeks");
  
        // Count property is used to get the
        // number of key/value pairs in fslist
        // It will give output 4
        Console.WriteLine(fslist.Count);
    }
}

chevron_right


Output:

0
4

Note:

  • Key/value pair can be accessed as a DictionaryEntry object.
  • The count is the number of elements which are actually present in the SortedList but capacity is the number of elements which can be stored by the SortedList object.
  • Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is automatically increased by reallocating the internal array before copying the old elements and adding the new elements.
  • Retrieving the value of this property is an O(1) operation.

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.