While writing some code to filter a collection using System.Linq I noticed a new method that I hadn't seen before: TryGetNonEnumeratedCount
This is a new feature introduced in C# 10. When using this method it will first check if it can provide the count without iterating over the collection. Why can this be useful? Let’s find out together…
Counting operations on IEnumerable<T>
The typical way to count the number of elements on an IEnumerable<T> is through the Count() method. This Count() method will already do some optimizations. It will first check if the IEnumerable<T> can be casted to an ICollection<T>. If that is the case, the count can be returned immediately and we don’t need to iterate over all the elements. If not, Count() will have to loop through all the elements, which can be an expensive operation and be a performance issue, especially when the list of elements is long.
If you want to avoid this performance penalty, you can use the TryGetNonEnumeratedCount() method. It will first check if it is ‘safe’ to do a count in a fast way, if not it will return nothing.
Let’s see this method in action:
The output will be like this:
If you try the same method on for example a DbSet, it will return false.