How to check if IEnumerable is null or empty?
I love string.IsNullOrEmpty
method. I'd love to have something that would allow the same functionality for IEnumerable. Is there such? Maybe some collection helper class? The reason I am asking is that in if
statements the code looks cluttered if the patter is (mylist != null && mylist.Any())
. It would be much cleaner to have Foo.IsAny(myList)
.
This post doesn't give that answer: IEnumerable is empty?.
Solution 1:
Sure you could write that:
public static class Utils {
public static bool IsAny<T>(this IEnumerable<T> data) {
return data != null && data.Any();
}
}
however, be cautious that not all sequences are repeatable; generally I prefer to only walk them once, just in case.
Solution 2:
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) {
return enumerable == null || !enumerable.Any();
}
Solution 3:
Here's a modified version of @Matt Greer's useful answer that includes a static wrapper class so you can just copy-paste this into a new source file, doesn't depend on Linq, and adds a generic IEnumerable<T>
overload, to avoid the boxing of value types that would occur with the non-generic version. [EDIT: Note that use of IEnumerable<T>
does not prevent boxing of the enumerator, duck-typing can't prevent that, but at least the elements in a value-typed collection will not each be boxed.]
using System.Collections;
using System.Collections.Generic;
public static class IsNullOrEmptyExtension
{
public static bool IsNullOrEmpty(this IEnumerable source)
{
if (source != null)
{
foreach (object obj in source)
{
return false;
}
}
return true;
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
if (source != null)
{
foreach (T obj in source)
{
return false;
}
}
return true;
}
}
Solution 4:
Another way would be to get the Enumerator and call the MoveNext() method to see if there are any items:
if (mylist != null && mylist.GetEnumerator().MoveNext())
{
// The list is not null or empty
}
This works for IEnumerable as well as IEnumerable<T>.
Solution 5:
The way I do it, taking advantage of some modern C# features:
Option 1)
public static class Utils {
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
return !(list?.Any() ?? false);
}
}
Option 2)
public static class Utils {
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
return !(list?.Any()).GetValueOrDefault();
}
}
And by the way, never use Count == 0
or Count() == 0
just to check if a collection is empty. Always use Linq's .Any()