哪种方法效果更好:.Any()与.Count()> 0?

末鹿安然 提交于 2020-08-05 17:49:40

问题:

in the System.Linq namespace, we can now extend our IEnumerable 's to have the Any() and Count() extension methods . System.Linq命名空间中,我们现在可以将IEnumerable扩展为具有Any()Count() 扩展方法

I was told recently that if i want to check that a collection contains 1 or more items inside it, I should use the .Any() extension method instead of the .Count() > 0 extension method because the .Count() extension method has to iterate through all the items. 最近,我被告知,如果我要检查一个集合包含在它里面1个或多个项目,我应该使用.Any()而不是扩展方法.Count() > 0扩展方法,因为.Count()扩展方法必须遍历所有项目。

Secondly, some collections have a property (not an extension method) that is Count or Length . 其次,某些集合具有CountLength 属性 (不是扩展方法)。 Would it be better to use those, instead of .Any() or .Count() ? 它会更好利用这些,而不是.Any().Count()

yea / nae ? 是/否?


解决方案:

参考一: https://stackoom.com/question/1HMq/哪种方法效果更好-Any-与-Count-gt
参考二: https://oldbug.net/q/1HMq/Which-method-performs-better-Any-vs-Count-0
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!