Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncPageable<T> Get first result asynchronously

Tags:

c#

async-await

I have AsyncPageable<T> and want to get only the first result from the list.

MS docs suggests using await foreach

// call a service method, which returns AsyncPageable<T>
AsyncPageable<SecretProperties> allSecretProperties = client.GetPropertiesOfSecretsAsync();

await foreach (SecretProperties secretProperties in allSecretProperties)
{
    Console.WriteLine(secretProperties.Name);
}

Is there any efficient way to get only the first result? Something like FirstOrDefaultAsync()?

At the moment I am using this code to get the first result.

var enumerator = response.Value.GetResultsAsync().GetAsyncEnumerator();
await enumerator.MoveNextAsync();
var result = enumerator.Current;
like image 872
Deivydas Voroneckis Avatar asked Apr 20 '26 01:04

Deivydas Voroneckis


1 Answers

Since AsyncPageable<T> implements IAsyncEnumerable<T>, you can install System.Linq.Async nuget and use the methods it provides:

var result = await allSecretProperties.FirstOrDefaultAsync();
like image 76
rytisk Avatar answered Apr 21 '26 15:04

rytisk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!