John K
John K

Reputation: 28869

How to know if an IEnumerable<ValueType> is empty, without counting all?

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

Answers (3)

Mark Rushakoff
Mark Rushakoff

Reputation: 258158

The .Any() extension method was designed for this case.

Upvotes: 4

BrokenGlass
BrokenGlass

Reputation: 160882

bool isEmpty = !myEnumerableReferenceTypeElements.Any();

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82335

Try using .Any()

bool isEmpty = !myEnumerable.Any();

From MSDN

Determines whether a sequence contains any elements.

Upvotes: 16

Related Questions