应该避免 IEnumerable 的 Count() 吗?

Should Count() of an IEnumerable be avoided?

一般来说,我使用 List,然后在我不再需要更新它们时将它们作为 IEnumerable 返回。

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

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

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

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 属性。 (非泛型 ICollection 的使用仅在 .NET 4 中引入;在 .NET 3.5 中它仅注意到 ICollection<T>。)

只有 documented 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.