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:
// C# Program to count the number // of elements in SortedList using System; using System.Collections; class Beginner { // 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 Beginner { // 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" , "Beginner" ); fslist.Add( "3" , "for" ); fslist.Add( "4" , "Beginner" ); // 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:
- https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.count?view=netframework-4.7.2
Contact Us