TryGetNonEnumeratedCount
Attempts to determine the number of elements in a sequence without forcing an enumeration. For those who are not yet using .NET 6
Source
public static class EnumerableExtensions
{
public static bool TryGetNonEnumeratedCount<T>(this IEnumerable<T> enumerable, out int count)
{
count = 0;
if (enumerable is ICollection<T> list)
{
count = list.Count;
return true;
}
return false;
}
}
Example
static void A(IEnumerable<int> data)
{
if (data.TryGetNonEnumeratedCount(out var count))
{
// We will get the count without enumeration.
}
else
{
// fallback
}
}
Author: Bartosz Adamczewski
Submitted on: 26 nov. 2021
Language: csharp
Type: System.Collections.Generic.IEnumerable<T>
Views: 2972