[英]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.