Skip to content
Related Articles

Related Articles

C# | Get the number of elements contained in SortedList
  • Last Updated : 01 Feb, 2019

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:






// 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);
    }
}
Output:
0

Example 2:




// 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);
    }
}
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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :