简体   繁体   English

在 IAsyncEnumerable 中使用 linq 类型方法的正确方法是什么?

[英]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.似乎没有任何包含对 .NET Core 打包的 IAsyncEnumerable 的 linq 支持。 What is the correct way to be able to do simple things such as ToList and Count?能够做 ToList 和 Count 之类的简单事情的正确方法是什么?

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.这是一个很好的问题,因为IAsyncEnumerable<T>上的 IntelliSense 中IAsyncEnumerable<T>没有任何有用的项目,并且带有默认的 .NET Core 应用程序的隐式框架引用。

It is expected that you would add the System.Linq.Async (know as Ix Async, see here ) package like this:预计您将添加System.Linq.Async (称为 Ix Async, 参见此处)包,如下所示:

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

Then you can use CountAsync , or ToListAsync :然后你可以使用CountAsyncToListAsync

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...正如评论中指出的那样,这些方法本身并没有那么有用,应该在您使用更强大的功能后使用它们,同时将数据保持为异步流,例如SelectAwaitWhereAwait等......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM