Schultz9999 Schultz9999 - 3 months ago 17
C# Question

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

Answer

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.