Should Count() of an IEnumerable be avoided?

╄→гoц情女王★ 提交于 2021-02-18 20:29:32

问题


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.

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

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


回答1:


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

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>.)

It's only documented for ICollection<T>, however:

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



来源:https://stackoverflow.com/questions/31815853/should-count-of-an-ienumerable-be-avoided

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!