Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 905
John K Avatar asked Mar 14 '11 16:03

John K


People also ask

How check if list is empty C#?

Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.

Can IEnumerable contain null?

An object collection such as an IEnumerable<T> can contain elements whose value is null.

How do I know if IEnumerable has an item?

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.


1 Answers

Try using .Any()

bool isEmpty = !myEnumerable.Any();

From MSDN

Determines whether a sequence contains any elements.

like image 183
Quintin Robinson Avatar answered Sep 20 '22 20:09

Quintin Robinson