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.

Prerequisites

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.

TryGetNonEnumeratedCount

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

Example

Lets for fun concatenate 3 lists:

var pair1 = new[]
{
    "Man1",
    "Woman1",
};

var pair2 = new[]
{
    "Man2",
    "Woman2",
};

var pair3 = new[]
{
    "Man3",
    "Woman3",
};

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");
    Console.WriteLine(countForce);
}

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");
    Console.WriteLine(count);
}

Download my examples form GitHub.

Microsoft TryGetNonEnumeratedCount documentation

Leave a Comment