TryGetNonEnumeratedCount: New LINQ extensions series

Maytham Fahmi
2 min readDec 19, 2021

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

Originally published at https://itbackyard.com on December 19, 2021.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Maytham Fahmi
Maytham Fahmi

Written by Maytham Fahmi

Maytham is a passionate software developer with more than ten years of experience. His motivation is to help transform ideas into production ready systems.

No responses yet

Write a response