Empty.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. #if INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  12. // https://learn.microsoft.com/en-us/dotnet/api/system.linq.asyncenumerable.empty?view=net-9.0-pp
  13. /// <summary>
  14. /// Returns an empty async-enumerable sequence.
  15. /// </summary>
  16. /// <typeparam name="TValue">The type used for the <see cref="IAsyncEnumerable{T}"/> type parameter of the resulting sequence.</typeparam>
  17. /// <returns>An async-enumerable sequence with no elements.</returns>
  18. public static IAsyncEnumerable<TValue> Empty<TValue>() => EmptyAsyncIterator<TValue>.Instance;
  19. internal sealed class EmptyAsyncIterator<TValue> : IAsyncPartition<TValue>, IAsyncEnumerator<TValue>
  20. {
  21. public static readonly EmptyAsyncIterator<TValue> Instance = new();
  22. public TValue Current => default!;
  23. public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken) => new(0);
  24. public IAsyncPartition<TValue> Skip(int count) => this;
  25. public IAsyncPartition<TValue> Take(int count) => this;
  26. public ValueTask<TValue[]> ToArrayAsync(CancellationToken cancellationToken) => new([]);
  27. public ValueTask<List<TValue>> ToListAsync(CancellationToken cancellationToken) => new([]);
  28. public ValueTask<Maybe<TValue>> TryGetElementAtAsync(int index, CancellationToken cancellationToken) => new(new Maybe<TValue>());
  29. public ValueTask<Maybe<TValue>> TryGetFirstAsync(CancellationToken cancellationToken) => new(new Maybe<TValue>());
  30. public ValueTask<Maybe<TValue>> TryGetLastAsync(CancellationToken cancellationToken) => new(new Maybe<TValue>());
  31. public ValueTask<bool> MoveNextAsync() => new(false);
  32. public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
  33. {
  34. cancellationToken.ThrowIfCancellationRequested(); // NB: [LDM-2018-11-28] Equivalent to async iterator behavior.
  35. return this;
  36. }
  37. public ValueTask DisposeAsync() => default;
  38. }
  39. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  40. }
  41. }