Skip to content

Instantly share code, notes, and snippets.

@aalmada
Created May 10, 2021 07:54
Show Gist options
  • Select an option

  • Save aalmada/95671bf1404ee42bdef4fb98e368132f to your computer and use it in GitHub Desktop.

Select an option

Save aalmada/95671bf1404ee42bdef4fb98e368132f to your computer and use it in GitHub Desktop.
public static int Count<TEnumerable, TEnumerator, TSource>(this TEnumerable source)
where TEnumerable : IValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IEnumerator<TSource>
{
var counter = 0;
using var enumerator = source.GetEnumerator();
checked
{
while (enumerator.MoveNext())
counter++;
}
return counter;
}
public static async ValueTask<int> CountAsync<TEnumerable, TEnumerator, TSource>(this TEnumerable source, CancellationToken cancellationToken = default)
where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IAsyncEnumerator<TSource>
{
var counter = 0;
var enumerator = source.GetAsyncEnumerator(cancellationToken);
await using (enumerator.ConfigureAwait(false))
{
checked
{
while (await enumerator.MoveNextAsync().ConfigureAwait(false))
counter++;
}
}
return counter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment