Check whether a HashSet is empty or not in C#
This post will discuss how to check whether a HashSet<T>
is empty or not in C#.
1. Using Enumerable.Any()
Method
The Enumerable.Any() method from LINQ is often used to determine whether any element of a sequence satisfies the specified predicate. If no predicate is supplied, the Any()
method simply checks whether the sequence contains any values or not. For example, the following code uses the Any()
method to check whether a HashSet<T>
is empty or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>(); bool isEmpty = !numbers.Any(); Console.WriteLine(isEmpty); // True } } |
The above code will throw a NullReferenceException
if the HashSet<T>
is null. We can easily use the null-conditional operator to check against a null, as shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = null; bool isNullOrEmpty = numbers?.Any() != true; Console.WriteLine(isNullOrEmpty); // True } } |
2. Using Count
Property
Alternatively, you can use the Count
property to check whether a collection is empty or not. The Count
property returns the total number of elements contained in a collection in constant time. The following example demonstrates its usage for a HashSet<T>
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>(); bool isEmpty = numbers?.Count == 0; Console.WriteLine(isEmpty); // True } } |
If the HashSet<T>
is not guaranteed to be null, the above code might throw an exception. To handle null references, consider adding the null-check before accessing the nullable fields.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>(); bool isNullOrEmpty = numbers != null && numbers.Count == 0; Console.WriteLine(isNullOrEmpty); // True } } |
Here’s an equivalent version using the Count()
method. Note that this uses LINQ.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>(); bool isNullOrEmpty = numbers != null && numbers.Count() == 0; Console.WriteLine(isNullOrEmpty); // True } } |
That’s all about checking whether a HashSet<T>
is empty or not 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 :)