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?.
I used simple if to check for it
check out my solution
The other best solution as below to check empty or not ?
just add
using System.Linq
and see the magic happening when you try to access the available methods in theIEnumerable
. Adding this will give you access to method namedCount()
as simple as that. just remember to check fornull value
before callingcount()
:)Here's the code from Marc Gravell's answer, along with an example of using it.
As he says, not all sequences are repeatable, so that code may sometimes cause problems, because
IsAny()
starts stepping through the sequence. I suspect what Robert Harvey's answer meant was that you often don't need to check fornull
and empty. Often, you can just check for null and then useforeach
.To avoid starting the sequence twice and take advantage of
foreach
, I just wrote some code like this:I guess the extension method saves you a couple of lines of typing, but this code seems clearer to me. I suspect that some developers wouldn't immediately realize that
IsAny(items)
will actually start stepping through the sequence. (Of course if you're using a lot of sequences, you quickly learn to think about what steps through them.)I built this off of the answer by @Matt Greer
He answered the OP's question perfectly.
I wanted something like this while maintaining the original capabilities of Any while also checking for null. I'm posting this in case anyone else needs something similar.
Specifically I wanted to still be able to pass in a predicate.
The naming of the extension method could probably be better.
Another way would be to get the Enumerator and call the MoveNext() method to see if there are any items:
This works for IEnumerable as well as IEnumerable<T>.