Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Count() and Count property

0.00/5 (No votes)
16 Oct 2012 3  
Count() and Count property

In this tip post I am going to discuss about the Count property and Count() method that used to return count of number of element in collection.


Count property

Each collection object which is inherited from ICollection<T> Interface has count property which returns number of element in collection.

Count() Function

But the things change when you make use of System.Linq namespace in you code. when you make use of this namespace you get Count() method which also returns you number of element in you collection. But the point to not here is Count() is extestion method of IEnumerable<T> class. Check the following images


Without using Linq namespace


With Using Linq namespace

 
IEnumerable<T> Source after query

 
After Converting Source to ICollection<T> type

 
Code on which I tested
List<string> lst = new List<string>() { "abc", "def" };
int a = lst.Count;
var b = lst.Where(x => x == "abc").Count();
List<string> ls = lst.Where(x => x == "abc").ToList<string>();
a= ls.Count;

If you are using Count() method on source which implements ICollection<T> interface than extension method make use of the Count property of it and returns no of element. If the source not implemented from the ICollection<T> than it do perform the operation on the element of source and return count of it.
 

Point to Note
-  

  •  As per MSDN : Retrieving the value of Count property is an O(1) operation.
  • Count() function perform the operation and return value, so its slower than count property.  

Conclusion  


Although its stated that Count() function make use of count property if the source implemented from ICollection<T> than use cont property, its better to use count property directly if source implemented ICollection<T> otherwise go for Count() get number of element in source. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here