Find Size of a List or Set in C#
This post will discuss how to find the size of a List or Set in C#.
1. Using Count Property
The standard solution to find the total number of elements in a List or Set is using its Count property. It returns the number of elements that are contained in the collection in O(1) time. The following example demonstrates its usage for a HashSet:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>() { 1, 2, 3, 4 }; int size = numbers.Count; Console.WriteLine(size); // 4 } } |
2. Using Count() Method
Alternatively, you can invoke LINQ’s Count() method on a collection to determine its size. The following code example demonstrates the usage of Count() method to count the elements in a HashSet.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>() { 1, 2, 3, 4 }; int size = numbers.Count(); Console.WriteLine(size); // 4 } } |
That’s all about finding the size of a List or Set in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)