How to check if IEnumerable is null or empty?

Schultz9999 picture Schultz9999 · Feb 18, 2011 · Viewed 220.5k times · Source

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?.

Answer

Marc Gravell picture Marc Gravell · Feb 18, 2011

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.