TryGetNonEnumeratedCount: New LINQ extensions series

TryGetNonEnumeratedCount is part of .NET 6. Since .NET 6 is released recently, it is a good opportunity to mention some of the new LINQ extensions methods. I will post a series of small articles focused on some these new or maybe less known LINQ methods.

In this article I am going to take TryGetNonEnumeratedCount LINQ method with some examples so it is easier to understand it.


To to use these new LINQ extensions you need to download and install this version of .NET 6.

I download and install Visual Studio 2022 in this article.


Attempts to determine the number of elements in a sequence without forcing an enumeration.


Lets for fun concatenate 3 lists:

var pair1 = new[]

var pair2 = new[]

var pair3 = new[]

IEnumerable<string> concatPairs = pair1.Concat(pair2).Concat(pair3);

and try to count them by classic way:

var countForce = concatPairs.Count();
if (countForce > 0)
    // do some stuff
    Console.WriteLine("Enforce enumeration to count");

Now lets count them in the new way without forcing an enumeration :

if (concatPairs.TryGetNonEnumeratedCount(out var count))
    // do some stuff
    Console.WriteLine("Try to count with out enforcing enumeration");

Download my examples form GitHub.

Microsoft TryGetNonEnumeratedCount documentation

Leave a Comment