0

I have an interface which specifies an IAsyncEnumerable<T> return value, but for a specific implementation I have the results cached in memory as a List<T>.

Is there a more straightforward way to return this list which already exists as an IAsyncEnumerable<T> without having to actually iterate over it? It seems list I shouldn't need the additional overhead of creating an iterator function.

public async IAsyncEnumerable<PartitionModel> GetAllPartitionsAsync([EnumeratorCancellation] CancellationToken cancellationToken = default)
{
    // _cache.GetOrAddAsync() returns List<PartitionModel>
    var list = await _cache.GetOrAddAsync(CacheKey, () => FetchAllPartitionsAsync(cancellationToken), CacheOptions);

    foreach (var item in list)
        yield return item;
}
Tobias J
  • 19,813
  • 8
  • 81
  • 66
  • A `List<>` doesn't implement `IAsyncEnumerable` so you can't just cast it. Even if you could, what would be the behavior? Block until everything is returned? Yield after every item? Yield after N items? That's not a decision that can be made by the runtime. – Panagiotis Kanavos Aug 23 '21 at 16:11
  • 1
    An extension method [`ToAsyncEnumerable`](https://github.com/dotnet/reactive/blob/main/Ix.NET/Source/System.Linq.Async/System/Linq/Operators/ToAsyncEnumerable.cs) for `IEnumerable`s is available in the [System.Linq.Async](https://www.nuget.org/packages/System.Linq.Async) package (owned by the [dotnetfoundation](https://www.nuget.org/profiles/dotnetfoundation)). – Theodor Zoulias Aug 23 '21 at 17:11
  • 1
    That still enumerates the list – Panagiotis Kanavos Aug 23 '21 at 17:36
  • 1
    @TheodorZoulias thanks, I had avoided using that package due to the namespace conflicts with EF Core until version 6 is released but I'll give it another look! https://github.com/dotnet/efcore/issues/24041 – Tobias J Aug 23 '21 at 19:40

0 Answers0