Reputation: 28869
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
Upvotes: 12
Views: 6980
Reputation: 82335
Try using .Any()
bool isEmpty = !myEnumerable.Any();
From MSDN
Determines whether a sequence contains any elements.
Upvotes: 16