如何将IEnumerable<IAsyncEnumerable<T>>转换为IAsyncEnumerable<T>?
把IEnumerable<IAsyncEnumerable>转换为IAsyncEnumerable的方法
有两种实用方式可以实现这个转换,具体如下:
方法一:使用System.Linq.Async库的SelectMany
如果你能引入NuGet包System.Linq.Async,直接用LINQ的SelectMany就能完成转换——该方法的重载专门支持嵌套异步枚举序列的扁平化:
using System.Linq; // 假设你的源变量定义如下 IEnumerable<IAsyncEnumerable<T>> nestedAsyncEnumerables = ...; // 调用SelectMany完成转换 IAsyncEnumerable<T> flattened = nestedAsyncEnumerables.SelectMany(seq => seq);
SelectMany会自动遍历外层的每个IAsyncEnumerable<T>,异步枚举每个序列的元素后,将所有元素按顺序合并为单一的IAsyncEnumerable<T>。
方法二:手动实现扩展方法(无需额外依赖)
如果不想引入第三方库,自己写一个简单的扩展方法也很容易:
public static async IAsyncEnumerable<T> Flatten<T>(this IEnumerable<IAsyncEnumerable<T>> source) { // 同步遍历外层的每个异步枚举序列 foreach (var asyncSeq in source) { // 异步遍历当前序列的所有元素并返回 await foreach (var item in asyncSeq) { yield return item; } } }
使用时直接调用这个扩展方法即可:
IAsyncEnumerable<T> flattened = nestedAsyncEnumerables.Flatten();
这个方法逻辑直观:先逐个取出外层的异步序列,再异步遍历每个序列的元素,最终将所有元素按顺序输出为一个异步枚举序列。
内容的提问来源于stack exchange,提问作者Glayson Patricio
相关产品推荐
相关产品推荐

