Contents
C# Linq Count Example
As is now customary on this site, lets start by diving in to an example of Linq Count, showing it in action:
var numbers = new List<int>() { 1, 2, 3 }; Console.WriteLine( numbers.Count());
This outputs:
3
ICollection Count Example
Hang on, you might be thinking, I’m not used to seeing brackets () after Count. Isn’t count a property? And the answer is that sometimes, particularly for objects implementing ICollection, it is. For example:
var numbers = new List<int>() { 1, 2, 3 }; Console.WriteLine( numbers.Count);
Which also outputs:
3
But the above isn’t IEnumerable.Count (System.Linq), it’s ICollection.Count (System.Collections.Generic).
What’s the difference between IEnumerable.Count() and IColection.Count?
When you’re working with a list (or some other object that implements both ICollection and IEnumerable) you have a choice when calling count – call it without () to use the ICollection property, or call it with the () to use the IEnumerable method:
var numbers = new List<int>() { 1, 2, 3, 4, 5 }; // ICollection property Console.WriteLine(numbers.Count); // IEnumerable method - only works if using System.Linq Console.WriteLine(numbers.Count());
Both return the same value, so what’s the difference?
Thanks to the wonder that is open source we can see that there really isn’t a difference. The following is taken from the .NET Core source code and shows part of the implementation of the Linq Contains method:
namespace System.Linq { public static partial class Enumerable { public static int Count<TSource>(this IEnumerable<TSource> source) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (source is ICollection<TSource> collectionoft) { return collectionoft.Count; } ... } } }
Here we can see (on line 12-14) that where possible, the IEnumerable method will call the property on the collection.
This means that whichever you opt for, you’ll get the same performance.
Conclusion
We’ve seen that for ICollections like List, you can use either the Count property or the count() method and you won’t suffer a significant performance hit. It’s mostly a matter of style.
Personally, I default to using the property if it’s available (it makes it clearer that the call is fairly performant) but some people prefer the use of Count() as it makes certain refactoring simpler, it’s ultimately personal preference.
Thanks man, exactly what I was looking for!
No problem, I’m glad it was helpful 🙂