iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔄

Converting IAsyncEnumerable<T> to List<T> in C#

に公開
2

Many Azure SDK methods return results as an AsyncPageable<T> class. Furthermore, calling the AsyncPageable<T>.AsPages method on it provides an IAsyncEnumerable<T> interface result. The IAsyncEnumerable<T> interface is known as an asynchronous stream and allows for efficient data reading, but unfortunately, it does not have a method to convert it directly to a List<T>.

While wondering if there was a good way to handle this, I discovered that System.Linq.Async contains a ToListAsync<T> method. This is a package included in Reactive Extensions.

https://www.nuget.org/packages/System.Linq.Async

The ToListAsync<T> method does not support subsequent method chaining by itself. Therefore, you need to connect it using the AsTask or ContinueWith methods. Here is a concrete code example:

var blobContainerClient = new BlobContainerClient("{{connection-string}}", "{{containe-rname}}");
var blobNames = await blobContainerClient
    .GetBlobsAsync()
    .ToListAsync()
    .AsTask()
    .ContinueWith(task => task.Result.Select(_ => _.Name));

This is also documented in the Microsoft documentation.

https://learn.microsoft.com/en-us/dotnet/azure/sdk/pagination?WT.mc_id=M365-MVP-5002941

Discussion

Mayuki SawatariMayuki Sawatari

ContinueWith メソッドを使わず

await blobContainerClient.GetBlobsAsync().Select(x => x.Name).ToListAsync();

または

var blobNames = (await blobContainerClient.GetBlobsAsync().ToListAsync())
    .Select(x => x.Name)
    .ToList();

ではどうでしょうか?

karamem0karamem0

コメントありがとうございます。
そうですね、await を () で囲むのが個人的に好きでなかったのでいつも ContinueWith を使っているのを忘れていました。ご指摘ありがとうございます!