Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 725
cubesnyc Avatar asked Nov 26 '19 23:11

cubesnyc


People also ask

What is IAsyncEnumerable in C#?

IAsyncEnumerable<T> exposes an enumerator that has a MoveNextAsync() method that can be awaited. This means a method that produces this result can make asynchronous calls in between yielding results.

Is it good to use Linq in C#?

Advantages of LINQStandardized way of querying multiple data sources: The same LINQ syntax can be used to query multiple data sources. Compile time safety of queries: It provides type checking of objects at compile time. IntelliSense Support: LINQ provides IntelliSense for generic collections.

How does Linq any work?

What is Linq Any in C#? The C# Linq Any Operator is used to check whether at least one of the elements of a data source satisfies a given condition or not. If any of the elements satisfy the given condition, then it returns true else return false. It is also used to check whether a collection contains some data or not.


1 Answers

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...

like image 87
Stuart Avatar answered Oct 04 '22 02:10

Stuart