Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the Count property of SortedList class in C#?
The Count property of the SortedList class in C# returns the number of key-value pairs stored in the collection. This read-only property is useful for determining the size of the sorted list and performing operations that depend on the collection's current size.
Syntax
Following is the syntax for accessing the Count property −
int count = sortedList.Count;
Return Value
The Count property returns an int value representing the total number of key-value pairs currently stored in the SortedList.
Example
The following example demonstrates how to use the Count property to get the number of elements in a SortedList −
using System;
using System.Collections;
namespace Demo {
class Program {
static void Main(string[] args) {
SortedList s = new SortedList();
s.Add("S1", "Electronics");
s.Add("S2", "Clothing");
s.Add("S3", "Appliances");
s.Add("S4", "Books");
s.Add("S5", "Accessories");
s.Add("S6", "Musical Instruments");
Console.WriteLine("Count = " + s.Count);
}
}
}
The output of the above code is −
Count = 6
Using Count with Dynamic Operations
The Count property is particularly useful when performing dynamic operations on the SortedList −
using System;
using System.Collections;
class Program {
static void Main() {
SortedList products = new SortedList();
Console.WriteLine("Initial count: " + products.Count);
products.Add("P001", "Laptop");
products.Add("P002", "Mouse");
Console.WriteLine("After adding 2 items: " + products.Count);
products.Remove("P001");
Console.WriteLine("After removing 1 item: " + products.Count);
products.Clear();
Console.WriteLine("After clearing: " + products.Count);
}
}
The output of the above code is −
Initial count: 0 After adding 2 items: 2 After removing 1 item: 1 After clearing: 0
Common Use Cases
-
Loop boundaries: Using Count to iterate through all elements safely.
-
Validation: Checking if the collection is empty before performing operations.
-
Capacity planning: Monitoring collection size for memory management.
-
Conditional logic: Making decisions based on the number of stored items.
Conclusion
The Count property of SortedList provides an efficient way to determine the number of key-value pairs in the collection. It automatically updates as items are added or removed, making it essential for collection management and iteration control.
