[英]How to aggregate results of an IAsyncEnumerable
我想问一下是否有计划或存在聚合IAsyncEnumerable
返回的方法? 那么鉴于下面的方法,为什么没有简洁的方法来汇总其结果?
public async IAsyncEnumerable<bool> GenerateAsyncEnumerable(int range)
{
foreach (var x in Enumerable.Range(0, range))
{
await Task.Delay(500 * x);
yield return x % 2 == 0;
}
}
当前情景
public async Task Main()
{
bool accum = true;
await foreach (var item in GenerateAsyncEnumerable(3))
{
accum &= item;
//have some side effects on each particular item of the sequence
}
Console.WriteLine($"Accumulator:{accum}");
}
期望的场景
我想在给定自定义聚合Func
聚合IAsyncEnumerable
的结果
public async Main()
{
bool result = await foreach (var item in GenerateAsyncEnumerable(3).Aggregate(true, (x, y) => x & y))
{
//have some side effects on each particular item of the sequence
}
}
PS我不喜欢(在第一种情况下)我必须添加一个额外的局部变量accum
来收集可枚举的结果。 我是否遗漏了什么,是否有一些我不知道的语法糖?
您可以使用System.Linq.Async包中的AggregateAsync
方法:
bool result = await GenerateAsyncEnumerable(3).AggregateAsync(true, (x, y) => x & y);
Console.WriteLine($"Result: {result}");
输出:
结果:错误
由ReactiveX团队开发的System.Linq.Async包为IAsyncEnumerable
提供了LINQ 操作符,这些操作符等同于那些 LINQ 为IEnumerable
提供的操作符。
这包括常见的运算符,如Select() 、 Where() 、 Take()等。 Aggregate
由AggregateAsync实现。
重载类似于Enumerable.Aggregate ,这意味着您可以编写:
bool result=await GenerateAsyncEnumerable(3).AggregateAsync(true, (x, y) => x & y);
AggregateAsync
以这种方式命名,因为它消耗整个可枚举并产生单个结果。 它需要await
调用才能工作。 但是,其他运算符(如Select
)接受一个IAsyncEnumerable
并生成一个新的。 没有必要等待他们。
您可以使用此命名约定根据等效Enumerable
运算符的名称查找所需的 Linq.Async 运算符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.