cubesnyc
cubesnyc

Reputation: 1545

What is the correct way to use linq type methods with IAsyncEnumerable?

There does not seem to be any included linq support for IAsyncEnumerable packaged with .NET Core. What is the correct way to be able to do simple things such as ToList and Count?

Upvotes: 22

Views: 9063

Answers (1)

Stuart
Stuart

Reputation: 5496

This is a good question, as there are next to no useful items in IntelliSense on IAsyncEnumerable<T> out of the box with the implicit framework reference you'd have with a default .NET Core app.

It is expected that you would add the System.Linq.Async (know as Ix Async, see here) package like this:

<PackageReference Include="System.Linq.Async" Version="4.0.0" />

Then you can use CountAsync, or ToListAsync:

async IAsyncEnumerable<int> Numbers()
{
    yield return 1;
    await Task.Delay(100);
    yield return 2;
}

var count = await Numbers().CountAsync();
var myList = await Numbers().ToListAsync();

As pointed out in a comment, these methods aren't that useful on their own, they should be used after you have used the more powerful features while keeping your data as an asynchronous stream, with things like SelectAwait and WhereAwait etc...

Upvotes: 24

Related Questions