Checking if a generic collection is empty with Linq and C#

This is a common issue for many developers. How do you quickly and efficiently determine whether a given non-null collection contains any valid non-empty elements .

The string class is cool because you can use the string.IsNullOrEmpty(yourstring); to test for null and/or empty. Unfortunately, generic collections don’t implement a similar method. There are two ways to deal with this. The first one requires you to write an extension for generic collections like this:

public static bool IsEmpty<T>(this IEnumerable<T> list)
{
    if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0;
    return !list.Any();
}

Alternatively, you can use the following statement:

if (Collection != null)
{
    isSet = Collection.Any(s => !string.IsNullOrEmpty(s));
}

This code will look for any element that is not null or empty. Please note that the Collection above is of type IList<string> but the implementation should be similar for other objects.

Happy coding…


  • Share this post on