How to check if IEnumerable is null or empty?

2020-01-24 19:40发布

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

19条回答
Deceive 欺骗
2楼-- · 2020-01-24 20:38

I use Bool IsCollectionNullOrEmpty = !(Collection?.Any()??false);. Hope this helps.

Breakdown:

Collection?.Any() will return null if Collection is null, and false if Collection is empty.

Collection?.Any()??false will give us false if Collection is empty, and false if Collection is null.

Complement of that will give us IsEmptyOrNull.

查看更多
登录 后发表回答