Does C# have IsNullOrEmpty for List/IEnumerable?
Solution 1:
nothing baked into the framework, but it's a pretty straight forward extension method.
See here
/// <summary>
/// Determines whether the collection is null or contains no elements.
/// </summary>
/// <typeparam name="T">The IEnumerable type.</typeparam>
/// <param name="enumerable">The enumerable, which may be null or empty.</param>
/// <returns>
/// <c>true</c> if the IEnumerable is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
{
return true;
}
/* If this is a list, use the Count property for efficiency.
* The Count property is O(1) while IEnumerable.Count() is O(N). */
var collection = enumerable as ICollection<T>;
if (collection != null)
{
return collection.Count < 1;
}
return !enumerable.Any();
}
Daniel Vaughan takes the extra step of casting to ICollection (where possible) for performance reasons. Something I would not have thought to do.
Solution 2:
Late update: since C# 6.0, the null-propagation operator may be used to express concise like this:
if ( list?.Count > 0 ) // For List<T>
if ( array?.Length > 0 ) // For Array<T>
or, as a cleaner and more generic alternative for IEnumerable<T>
:
if ( enumerable?.Any() ?? false )
Note 1: all upper variants reflect actually IsNotNullOrEmpty
, in contrast to OP question (quote):
Because of operator precedence
IsNullOrEmpty
equivalents look less appealing:if (!(list?.Count > 0))
Note 2: ?? false
is necessary, because of the following reason (summary/quote from this post):
?.
operator will returnnull
if a child member isnull
. But [...] if we try to get a non-Nullable
member, like theAny()
method, that returnsbool
[...] the compiler will "wrap" a return value inNullable<>
. For example,Object?.Any()
will give usbool?
(which isNullable<bool>
), notbool
. [...] Since it can't be implicitly casted tobool
this expression cannot be used in theif
Note 3: as a bonus, the statement is also "thread-safe" (quote from answer of this question):
In a multithreaded context, if [enumerable] is accessible from another thread (either because it's a field that's accessible or because it's closed over in a lambda that is exposed to another thread) then the value could be different each time it's computed [i.e.prior null-check]
Solution 3:
There is nothing built in.
It is a simple extension method though:
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
if(enumerable == null)
return true;
return !enumerable.Any();
}
Solution 4:
var nullOrEmpty = list == null || !list.Any();
Solution 5:
Putting together the previous answers into a simple extension method for C# 6.0+:
public static bool IsNullOrEmpty<T>(this IEnumerable<T> me) => !me?.Any() ?? true;