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
Get the number of elements contained in Collection in C#
The Count property in C# provides a simple way to determine the number of elements contained in a Collection<T>. This property is available for all collection types that implement the ICollection<T> interface and returns an integer value representing the current element count.
Syntax
Following is the syntax for using the Count property −
Collection<T> collection = new Collection<T>(); int count = collection.Count;
Using Count with String Collection
The following example demonstrates how to get the count of elements in a string collection −
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<string> col = new Collection<string>();
col.Add("Andy");
col.Add("Kevin");
col.Add("John");
col.Add("Kevin");
col.Add("Mary");
col.Add("Katie");
col.Add("Barry");
col.Add("Nathan");
col.Add("Mark");
Console.WriteLine("Count of elements = "+ col.Count);
Console.WriteLine("Iterating through the collection...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
}
The output of the above code is −
Count of elements = 9 Iterating through the collection... Andy Kevin John Kevin Mary Katie Barry Nathan Mark
Using Count with Integer Collection and Dynamic Updates
This example shows how the Count property updates dynamically as elements are added or removed from the collection −
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main() {
Collection<int> col = new Collection<int>();
col.Add(10);
col.Add(20);
col.Add(30);
col.Add(40);
col.Add(50);
col.Add(60);
col.Add(70);
col.Add(80);
Console.WriteLine("Elements in the Collection...");
foreach(int val in col) {
Console.WriteLine(val);
}
Console.WriteLine("Does the collection has the element 70? = "+col.Contains(70));
Console.WriteLine("Count of elements = " + col.Count);
col.Clear();
Console.WriteLine("Count of elements (updated) = " + col.Count);
}
}
The output of the above code is −
Elements in the Collection... 10 20 30 40 50 60 70 80 Does the collection has the element 70? = True Count of elements = 8 Count of elements (updated) = 0
Count vs Length vs Size
| Property | Used With | Description |
|---|---|---|
Count |
Collections (List, Collection, etc.) | Returns current number of elements |
Length |
Arrays and strings | Returns fixed size or character count |
Capacity |
List<T> | Returns internal array size (? Count) |
Conclusion
The Count property provides an efficient way to determine the number of elements in a Collection<T>. It updates automatically as elements are added or removed, making it ideal for tracking collection size dynamically during runtime operations.
