【问题标题】:How to aggregate results of an IAsyncEnumerable如何聚合 IAsyncEnumerable 的结果
【发布时间】:2020-06-09 01:39:40
【问题描述】:

我想问是否有计划或存在方法来汇总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
    }
}

P.S 我不喜欢(在第一种情况下)我必须添加一个额外的局部变量 accum 来收集可枚举的结果。我是否遗漏了什么,是否有一些我不知道的语法糖?

【问题讨论】:

  • 你可以编写你自己的扩展方法来返回一个新的IAsyncEnumerable?
  • 所有这些方法都是System.Linq.Async的一部分,包括AggregateAsync
  • 正如@PanagiotisKanavos 提到的,库System.Linq.Async 下有扩展方法。其中之一是ToAsyncEnumerable,但在使用时要小心。见stackoverflow.com/questions/59956623/…

标签: c# aggregate c#-8.0 iasyncenumerable


【解决方案1】:

您可以使用AggregateAsync 包中的AggregateAsync 方法:

bool result = await GenerateAsyncEnumerable(3).AggregateAsync(true, (x, y) => x & y);
Console.WriteLine($"Result: {result}");

输出:

结果:错误

【讨论】:

    【解决方案2】:

    ReactiveX 团队开发的System.Linq.Async 包为IAsyncEnumerable 提供LINQ operators,相当于为IEnumerable 提供的那些LINQ。

    这包括Select()Where()Take()等常用运算符。AggregateAggregateAsync实现。

    重载类似于Enumerable.Aggregate ,这意味着你可以写:

    bool result=await GenerateAsyncEnumerable(3).AggregateAsync(true, (x, y) => x & y);
    

    AggregateAsync 之所以这样命名,是因为它消耗了整个枚举并产生了一个结果。它需要一个await 调用才能工作。不过,像Select 这样的其他运算符接受IAsyncEnumerable 并生成一个新的。没有必要等待他们。

    您可以使用此命名约定根据等效 Enumerable 运算符的名称查找所需的 Linq.Async 运算符

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      相关资源
      最近更新 更多