Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
266 views
Welcome To Ask or Share your Answers For Others

1 Answer

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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...