DEV Community

Shirin Monzavi
Shirin Monzavi

Posted on

๐‚๐จ๐ฎ๐ง๐ญ ๐•๐ฌ ๐‚๐จ๐ฎ๐ง๐ญ() ๐ข๐ง ๐‚# ๐‹๐ข๐ฌ๐ญ<๐“>?

๐–๐ก๐š๐ญ ๐ข๐ฌ ๐‚๐จ๐ฎ๐ง๐ญ ๐ข๐ง ๐‹๐ข๐ฌ๐ญ<๐“>?
Count is a property of many collections in .Net and its value represents the number of elements in the collection. Its time complexity is O(1).

๐–๐ก๐š๐ญ ๐ข๐ฌ ๐‚๐จ๐ฎ๐ง๐ญ() ๐ข๐ง ๐‹๐ข๐ฌ๐ญ<๐“>?
Count() is LINQ extension method for counting elements of a List.
At first, LINQ checks the type, if it is type of collection, it uses the count property. Otherwise, it iterates through all elements to count them. Its time complexity is O(n).

๐Ÿ’ฏ๐ƒ๐จ ๐ฐ๐ž ๐ซ๐ž๐š๐ฅ๐ฅ๐ฒ ๐œ๐š๐ซ๐ž ๐ญ๐ก๐ž ๐๐ข๐Ÿ๐Ÿ๐ž๐ซ๐ž๐ง๐œ๐ž?
Yes! For large datasets, itโ€™s better to use the Count property instead of the Count() method whenever possible, because Count() still has the overhead of checking the type and calling the property.

โ“ ๐‡๐š๐ฏ๐ž ๐ฒ๐จ๐ฎ ๐ž๐ฏ๐ž๐ซ ๐Ÿ๐š๐œ๐ž๐ ๐ฐ๐ข๐ญ๐ก ๐ฌ๐ฎ๐œ๐ก ๐ฉ๐ž๐ซ๐Ÿ๐จ๐ซ๐ฆ๐š๐ง๐œ๐ž ๐ข๐ฌ๐ฌ๐ฎ๐ž? ๐’๐ก๐š๐ซ๐ž ๐ฒ๐จ๐ฎ๐ซ ๐ž๐ฑ๐ฉ๐ž๐ซ๐ข๐ž๐ง๐œ๐ž.

Top comments (0)