Without counting all the elements in an IEnumerables<T>
collection of struct
elements, what is the best way to detect if it is empty?
For example, on class
elements I would normally test with first or default:
myEnumerableReferenceTypeElements.FirstOrDefault() == null
because null is not normally a valid value in collections being iterated.
However, in the case of value types where all values must be in a predefined range, the default value (e.g. int default of 0) is also a viable item in the collection.
myValueTypeInt32Elements.FirstOrDefault() == 0 // can't tell if empty for sure
Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.
An object collection such as an IEnumerable<T> can contain elements whose value is null.
Use Any() Instead of Count() To See if an IEnumerable Has Any Objects. An IEnumerable is an implementation that supports simple iteration using an enumerator.
Try using .Any()
bool isEmpty = !myEnumerable.Any();
From MSDN
Determines whether a sequence contains any elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With