Empty.cs 2.6 KB

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