是否应该避免IEnumerable的Count()? [英] Should Count() of an IEnumerable be avoided?

查看:41
本文介绍了是否应该避免IEnumerable的Count()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我使用的是 List ,然后在不再需要更新它们时以 IEnumerable 的形式返回它们.

In general, I am using a List and then returning them as IEnumerable when I no longer need to update them.

但是,我遇到了一个问题,我实际上需要枚举它们,但首先需要知道计数.

However, I ran into an issue where I actually need to enumerate through them but first need to know the count.

IEnumerable 会枚举每个项目并找到计数(O(N)),还是依赖于 List 的Count属性(O(1))?

Will IEnumerable enumerate every item and find the count (O(N)), or will it rely on List's Count property (O(1))?

此外,如果 IEnumerable 是LINQ查询的结果怎么办?

Also, what if the IEnumerable is the result of a LINQ query?

推荐答案

IEnumerable会枚举每个项目并找到计数(O(N)),还是依赖于List的Count属性(O(1))?

Will IEnumerable enumerate every item and find the count (O(N)), or will it rely on List's Count property (O(1))?

它将使用 Count 属性.基本上,实现会检查对象是否实现 ICollection< T> ICollection ,如果是,则调用相关的 Count 属性.(仅在.NET 4中引入了对非通用 ICollection 的使用;在.NET 3.5中,它仅注意到了 ICollection< T> .)

It will use the Count property. Basically the implementation checks whether or not the object implements ICollection<T> or ICollection, and calls the relevant Count property if so. (The use of the non-generic ICollection was only introduced in .NET 4; in .NET 3.5 it only noticed ICollection<T>.)

这只是 已记录 ICollection< T> 的a>,

如果源的类型实现 ICollection< T> ,则该实现用于获取元素计数.否则,此方法将确定计数.

If the type of source implements ICollection<T>, that implementation is used to obtain the count of elements. Otherwise, this method determines the count.

这篇关于是否应该避免IEnumerable的Count()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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