AsyncPageable<T> Get first result asynchronously

Viewed 3962

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;
2 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();

Just wrap what you have in an extension method.

// hrmmm, im not sure
public static async Task<T> FirstOrDefaultAsync<T>(this IAsyncEnumerable<T> enumerable)
{
   await foreach (var item in enumerable)
      return item;
   return default;
}

// This is more efficient 
public static async Task<T> FirstOrDefaultAsync2<T>(this IAsyncEnumerable<T> enumerable)
{
   var enumerator = enumerable.GetAsyncEnumerator();
   await enumerator.MoveNextAsync();
   return enumerator.Current;
}

Check the IL to them both here

Related