SkipLast.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. public static IAsyncEnumerable<TSource> SkipLast<TSource>(this IAsyncEnumerable<TSource> source, int count)
  13. {
  14. if (source == null)
  15. throw Error.ArgumentNull(nameof(source));
  16. if (count <= 0)
  17. {
  18. // Return source if not actually skipping, but only if it's a type from here, to avoid
  19. // issues if collections are used as keys or otherwise must not be aliased.
  20. if (source is AsyncIteratorBase<TSource>)
  21. {
  22. return source;
  23. }
  24. count = 0;
  25. }
  26. return Create(Core);
  27. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  28. {
  29. var queue = new Queue<TSource>();
  30. await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false);
  31. while (await e.MoveNextAsync())
  32. {
  33. if (queue.Count == count)
  34. {
  35. do
  36. {
  37. yield return queue.Dequeue();
  38. queue.Enqueue(e.Current);
  39. }
  40. while (await e.MoveNextAsync());
  41. break;
  42. }
  43. else
  44. {
  45. queue.Enqueue(e.Current);
  46. }
  47. }
  48. }
  49. }
  50. }
  51. }