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?.
Without custom helpers I recommend either
?.Any() ?? false
or?.Any() == true
which are relatively concise and only need to specify the sequence once.When I want to treat a missing collection like an empty one, I use the following extension method:
This function can be combined with all LINQ methods and
foreach
, not just.Any()
, which is why I prefer it over the more specialized helper functions people are proposing here.my own extension method to check Not null and Any
This may help
Starting with C#6 you can use null propagation:
myList?.Any() == true
If you still find this too cloggy or prefer a good ol' extension method, I would recommend Matt Greer and Marc Gravell's answers, yet with a bit of extended functionality for completeness.
Their answers provide the same basic functionality, but each from another perspective. Matt's answer uses the
string.IsNullOrEmpty
-mentality, whereas Marc's answer takes Linq's.Any()
road to get the job done.I am personally inclined to use the
.Any()
road, but would like to add the condition checking functionality from the method's other overload:So you can still do things like :
myList.AnyNotNull(item=>item.AnswerToLife == 42);
as you could with the regular.Any()
but with the added null checkNote that with the C#6 way:
myList?.Any()
returns abool?
rather than abool
, which is the actual effect of propagating nullI use this one:
Ejem: