Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...