Count vs Any

We use Count() extension method to check number of items in a collection. I saw many of the developers use Count() to check if the collection is non-empty. For me, it is a bad practice as Count() goes on checking the collection even if the match found at the beginning.

For this, C# provides a better extension method called Any(). It halts as soon as the match founds. Lets observe this with an example:

  1. var collection = new ObservableCollection<Person>(){new Person{Name="Arunava",ID=1},new Person{Name="Arunava",ID=2},new Person{Name="Arun",ID=1}};  
  2. var exists = collection.Count(c => c.ID == 1);  
  3. var any=collection.Any(c=>c.ID==1);  
  4. Console.WriteLine(exists);  
  5. Console.WriteLine(any);  

You can see that “exists=2” and if you use F11 you will see the counter iterates thrice where “any=true” does it only once.

Note that Any(), like Count() can be called with no parameters (besides the implicit extension method source parameter) which tells you if the list contains any item at all (that is, if it’s not empty):

  1. var isEmpty=!Collection.Any();  
  2. var isEmpty=Collection.Count()==0; 

If the sequence is something like a list or array it may not matter because they have a constant time – O(1) . But it’s always the best practice to use the Any() for checking the condition.

In addition there is no performance short-cut on Count() with the condition, so if you only care that there’s at least one match and not how many,Any() is again the better choice.