转换IAsyncEnumerable到列表 [英] Convert IAsyncEnumerable to List

查看:178
本文介绍了转换IAsyncEnumerable到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此在C#8中,我们添加了 IAsyncEnumerable 接口.

So in C#8 we got the addition of the IAsyncEnumerable interface.

如果我们有一个普通的 IEnumerable ,我们可以制作一个 List 或几乎我们想要的其他任何集合.多亏了Linq.

If we have a normal IEnumerable we can make a List or pretty much any other collection we want out of it. Thanks to Linq there.

var range = Enumerable.Range(0, 100);
var list = range.ToList();

现在我想将我的 IAsyncEnumerable 转换为 List ,这当然是异步的.该情况下已经有Linq实现了吗?如果没有,那我该如何转换呢?

Well now I want to convert my IAsyncEnumerable to a List and this of course asynchronously. Are there already Linq implementations for that case? If there isn't, how could I convert it myself then?

推荐答案

当然-您只需要ToListAsync()方法.nuget.org/packages/System.Linq.Async/"rel =" noreferrer> System.Linq.Async NuGet包.这是一个完整的示例:

Sure - you just need the ToListAsync() method, which is in the System.Linq.Async NuGet package. Here's a complete example:

项目文件:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

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

</Project>

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        IAsyncEnumerable<string> sequence = GetStringsAsync();
        List<string> list = await sequence.ToListAsync();
        Console.WriteLine(list.Count);
    }

    static async IAsyncEnumerable<string> GetStringsAsync()
    {
        yield return "first";
        await Task.Delay(1000);
        yield return "second";
        await Task.Delay(1000);
        yield return "third";
    }
}

这篇关于转换IAsyncEnumerable到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆