Empty.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. /// <summary>
  12. /// Returns an empty async-enumerable sequence.
  13. /// </summary>
  14. /// <typeparam name="TValue">The type used for the <see cref="IAsyncEnumerable{T}"/> type parameter of the resulting sequence.</typeparam>
  15. /// <returns>An async-enumerable sequence with no elements.</returns>
  16. public static IAsyncEnumerable<TValue> Empty<TValue>() => EmptyAsyncIterator<TValue>.Instance;
  17. internal sealed class EmptyAsyncIterator<TValue> : IAsyncPartition<TValue>, IAsyncEnumerator<TValue>
  18. {
  19. public static readonly EmptyAsyncIterator<TValue> Instance = new();
  20. public TValue Current => default!;
  21. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken) => new(0);
  22. public IAsyncPartition<TValue> Skip(int count) => this;
  23. public IAsyncPartition<TValue> Take(int count) => this;
  24. public ValueTask<TValue[]> ToArrayAsync(CancellationToken cancellationToken) => new([]);
  25. public ValueTask<List<TValue>> ToListAsync(CancellationToken cancellationToken) => new([]);
  26. public ValueTask<Maybe<TValue>> TryGetElementAtAsync(int index, CancellationToken cancellationToken) => new(new Maybe<TValue>());
  27. public ValueTask<Maybe<TValue>> TryGetFirstAsync(CancellationToken cancellationToken) => new(new Maybe<TValue>());
  28. public ValueTask<Maybe<TValue>> TryGetLastAsync(CancellationToken cancellationToken) => new(new Maybe<TValue>());
  29. public ValueTask<bool> MoveNextAsync() => new(false);
  30. public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
  31. {
  32. cancellationToken.ThrowIfCancellationRequested(); // NB: [LDM-2018-11-28] Equivalent to async iterator behavior.
  33. return this;
  34. }
  35. public ValueTask DisposeAsync() => default;
  36. }
  37. }
  38. }