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?.
The returned IEnumerable<> might be empty, but it will never be null .
enumerable. Any() is the cleanest way to check if there are any items in the list.
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.
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) { return enumerable == null || !enumerable.Any(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With