C# Count() Extension Method Performance

左心房为你撑大大i 提交于 2019-11-29 15:56:41

It doesn't look for a Count property by name, but it does check whether it implements ICollection<T>, and then uses that type's Count property. From the documentation:

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

(Obviously this only applies to the overload which doesn't take a predicate.)

So, if you want to obtain the count efficiently, make sure you implement ICollection<T>.

Yes, the Enumerable.Count method will indeed look for ICollection<T> and use it's Count property if found. You can verify this by looking at Enumerable.Count in reflector.

This is only true though if you use the Count extension method which takes no additional parameters. If you use the version which takes a predicate it will walk the enumerable elements.

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