A method returns a sequence, IEnumerable<T>
, and you now want to check if it is empty. How do you recommend doing that? I'm looking for both good readability and good performance.
The first and most obvious way is to check that the count is greater than zero:
if(sequence.Count() == 0)
Has decent readability, but terrible performance since it has to actually go through the whole sequence.
A method that I sometimes use is the following:
if(!sequence.Any())
This doesn't (as far as I know) have to go through the whole sequence, but the readability is a bit backwards and awkward. (Reads a lot better if we are checking that the sequence is not empty though).
Another option is to use First
in a try-catch, like this:
try
{
sequence.First();
}
catch(InvalidOperationException)
{
// Do something
}
Not a very pretty solution, and probably slower too, since it is using exceptions and stuff. Could prevent that by using FirstOrDefault
of course, except you would have a big problem if the first item in the sequence actually was the default value ;)
So, any other ways to check if a sequence is empty? Which one do you usually use? Which one do you recommend to use?
Note: For optimal readability I would probably put one of the above snippets in an IsEmpty
extension method, but I am still curious since I would have to do something inside that method as well :p