Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 820
Schultz9999 Avatar asked Feb 18 '11 22:02

Schultz9999


People also ask

Can an IEnumerable be null?

The returned IEnumerable<> might be empty, but it will never be null .

How do I know if IEnumerable has an item?

enumerable. Any() is the cleanest way to check if there are any items in the list.


2 Answers

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.

like image 56
Marc Gravell Avatar answered Sep 23 '22 17:09

Marc Gravell


public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) {     return enumerable == null || !enumerable.Any(); } 
like image 44
Matt Greer Avatar answered Sep 21 '22 17:09

Matt Greer