Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended way to check if a sequence is empty

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

like image 301
Svish Avatar asked Jan 19 '10 15:01

Svish


People also ask

How do you check if a list is empty or null?

The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.

Can sequences be empty?

You can create sequences by using sequence expressions, as described previously, or by using certain functions. You can create an empty sequence by using Seq. empty, or you can create a sequence of just one specified element by using Seq.


1 Answers

I would use !sequence.Any(), personally.

If you really need to, you could always write your own extension method:

public static bool IsEmpty<T>(this IEnumerable<T> source) {     return !source.Any(); } 

Then you can write:

if (sequence.IsEmpty()) 
like image 64
Jon Skeet Avatar answered Sep 22 '22 03:09

Jon Skeet