ienumerable<> count vs ienumerable.tolist()。计数

发布于 2025-02-12 03:35:52 字数 347 浏览 0 评论 0原文

我试图找到列表是否为空。最有效的方法是什么。

IEnumerable<int> TestProp={get; set;}

该测试程序将通过另一种方法填充。当我尝试检查列表是否为空时,我必须至少做很多100次。 现在,我看到了它,据

var cnt=TestProp.ToList().Count>0;

我所知,iEnumerable将尝试通过转换为Icollection来查找计数属性,但是我在这里寻找的是查找非空列表的最佳性能方法。我以某种方式在这里不需要tolist()

I am trying to find if a list is Empty. Whats the most efficient way.

IEnumerable<int> TestProp={get; set;}

this TestProb will be populated by another method. when I try to check if list is empty and I have to do this many times few 100s atleast.
Right now I see it as

var cnt=TestProp.ToList().Count>0;

I know IEnumerable will try to find Count property by converting to ICollection but what I am looking here is best performant way for finding non empty list. I somehow feel ToList() is not needed here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

娇纵 2025-02-19 03:35:52

您可以编写自己的扩展名

public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
{
    return source != null && source.Any();
}

if (TestProp.NotNullOrEmpty())

可以使用,

if (TestProp?.Any() == true)

也可以使用布尔值进行比较,以便您不能这样使用,

if (TestProp?.Any())

因为testprop?.any()将返回nullable&lt; bool&bool&gt; < /代码>

you can write your own extension

public static bool NotNullOrEmpty<T>(this IEnumerable<T> source)
{
    return source != null && source.Any();
}

and call

if (TestProp.NotNullOrEmpty())

or you can use

if (TestProp?.Any() == true)

but you must be compare with boolean value so you cannot use like this

if (TestProp?.Any())

because TestProp?.Any() will return Nullable<bool>

蓝颜夕 2025-02-19 03:35:52

通常,答案是使用.yany()
如果您想要一个更完整的答案,可以找到它在这里

In general, the answer is to use .Any()
If you want a more complete answer you can find it here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文