推荐的方法来检查序列是否为空 [英] Recommended way to check if a sequence is empty
问题描述
一个方法返回一个序列IEnumerable<T>
,现在您要检查它是否为空.您如何建议这样做?我正在寻找良好的可读性和良好的性能.
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())
(据我所知)这不必遍历整个序列,但是可读性有点落后和尴尬. (如果我们要检查序列是否为 not 为空,则阅读效果会更好).
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).
另一种选择是在尝试捕获中使用First
,如下所示:
Another option is to use First
in a try-catch, like this:
try
{
sequence.First();
}
catch(InvalidOperationException)
{
// Do something
}
这不是一个非常漂亮的解决方案,并且可能也更慢,因为它使用了异常和填充.当然可以通过使用FirstOrDefault
来防止这种情况,除非序列中的第一项实际上是默认值;)
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?
注意:为了获得最佳的可读性,我可能会将上述片段之一放在IsEmpty
扩展方法中,但我仍然很好奇,因为我必须在该方法中做点事情以及:p
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
推荐答案
我个人会使用!sequence.Any()
.
如果确实需要,则可以始终编写自己的扩展方法:
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();
}
然后您可以编写:
if (sequence.IsEmpty())
这篇关于推荐的方法来检查序列是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!