Determining
“whether a collection is non-empty” is considered as one of the most basic and
simple algorithms and generally coded as:
For
collections that can grow dynamically i.e. List, Dictionary, etc. such a code
can be very costly in some circumstances.
If you’re
using property of ICollection class, there is no problem. You can safely
continue use them for framework collection classes since it keeps the count
pre-calculated.
If you are
using
function of IEnumarable interface, take a little notice. Because implementation
of
function over the .NET Framework collection classes calculate the
count by iterating through all elements in the collection.
For
collections that contain thousands or millions of element, that cost is highly
redundant for such a simple “Is Non-Empty?” operation.
The code
below determines “if the collection is non-empty” without counting and very
quickly:
C# Code:
A shortcut for IEnumerable<T> classes can be:
C# Code: