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

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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Maytham Fahmi

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.

More from Medium

[Dot Net Core](Graphic series )6. MiddleWare –How to work in .NET Core

How to write a unit test for your custom attribute which extends ActionFilterAttribute in c# .net

Technologies And Skills of Every Dot Net Developer

Creating static IP proxy for C# run in GCE using squid.