Pranay Rana: Count() and Count property

Thursday, July 26, 2012

Count() and Count property

In this small 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.

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

No comments:

Post a Comment