Skip.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. public static IAsyncEnumerable<TSource> Skip<TSource>(this IAsyncEnumerable<TSource> source, int count)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. if (count <= 0)
  16. {
  17. // Return source if not actually skipping, but only if it's a type from here, to avoid
  18. // issues if collections are used as keys or otherwise must not be aliased.
  19. if (source is AsyncIterator<TSource>)
  20. {
  21. return source;
  22. }
  23. count = 0;
  24. }
  25. return new SkipAsyncIterator<TSource>(source, count);
  26. }
  27. private sealed class SkipAsyncIterator<TSource> : AsyncIterator<TSource>
  28. {
  29. private readonly int count;
  30. private readonly IAsyncEnumerable<TSource> source;
  31. private int currentCount;
  32. private IAsyncEnumerator<TSource> enumerator;
  33. public SkipAsyncIterator(IAsyncEnumerable<TSource> source, int count)
  34. {
  35. Debug.Assert(source != null);
  36. this.source = source;
  37. this.count = count;
  38. currentCount = count;
  39. }
  40. public override AsyncIterator<TSource> Clone()
  41. {
  42. return new SkipAsyncIterator<TSource>(source, count);
  43. }
  44. public override async Task DisposeAsync()
  45. {
  46. if (enumerator != null)
  47. {
  48. await enumerator.DisposeAsync().ConfigureAwait(false);
  49. enumerator = null;
  50. }
  51. await base.DisposeAsync().ConfigureAwait(false);
  52. }
  53. protected override async Task<bool> MoveNextCore()
  54. {
  55. switch (state)
  56. {
  57. case AsyncIteratorState.Allocated:
  58. enumerator = source.GetAsyncEnumerator();
  59. // skip elements as requested
  60. while (currentCount > 0 && await enumerator.MoveNextAsync().ConfigureAwait(false))
  61. {
  62. currentCount--;
  63. }
  64. if (currentCount <= 0)
  65. {
  66. state = AsyncIteratorState.Iterating;
  67. goto case AsyncIteratorState.Iterating;
  68. }
  69. break;
  70. case AsyncIteratorState.Iterating:
  71. if (await enumerator.MoveNextAsync().ConfigureAwait(false))
  72. {
  73. current = enumerator.Current;
  74. return true;
  75. }
  76. break;
  77. }
  78. await DisposeAsync().ConfigureAwait(false);
  79. return false;
  80. }
  81. }
  82. }
  83. }