检查如果列表是空的LINQ [英] Checking if a list is empty with LINQ

查看:156
本文介绍了检查如果列表是空的LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是确定一个列表是空的最佳(以速度和可读性考虑在内)的方式?即使列表类型的的IEnumerable< T> 并没有Count属性

现在,我折腾了这个之间:

 如果(myList.Count()== 0){...}
 

和这样的:

 如果(!myList.Any()){...}
 

我的猜测是,第二个选项是更快,因为它会带回来的结果,只要它看到的第一个项目,而第二个选项(对于一个IEnumerable)需要访问每一个项目,返回计数

话虽这么说,没有第二个选项看起来可读吗?这将您preFER?或者,你能想出更好的方法来测试空单?

修改 @ lassevk的反应似乎是最合理的,加上位运行时的检查,如果可以使用缓存的数量,像这样的:

 公共静态布尔的IsEmpty< T>(这IEnumerable的< T>名单)
{
    如果(名单的ICollection< T>)收益率((ICollection的< T>)名单).Count之间的== 0;

    返回list.Any()!;
}
 

解决方案

你可以这样做:

 公共静态布尔的IsEmpty< T>(这IEnumerable的< T>源)
{
    如果(来源== NULL)
        返回true; //或者抛出一个异常
    返回source.Any()!;
}
 

修改:使用.Count之间的方法要快,如果底层源实际上有一个快速的Count属性需要注意的是简单的。上面的一个有效的优化将是检测的几个基本类型,并简单地使用,而不是。任何()方法的的.Count之间的财产,但随后回落到。任何()如果不能保证可。

What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type IEnumerable<T> and doesn't have a Count property.

Right now I'm tossing up between this:

if (myList.Count() == 0) { ... }

and this:

if (!myList.Any()) { ... }

My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count.

That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list?

Edit @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this:

public static bool IsEmpty<T>(this IEnumerable<T> list)
{
    if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0;

    return !list.Any();
}

解决方案

You could do this:

public static Boolean IsEmpty<T>(this IEnumerable<T> source)
{
    if (source == null)
        return true; // or throw an exception
    return !source.Any();
}

Edit: Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the .Count property of those, instead of the .Any() approach, but then fall back to .Any() if no guarantee can be made.

这篇关于检查如果列表是空的LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆