Skip.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. namespace System.Linq
  6. {
  7. public static partial class AsyncEnumerable
  8. {
  9. /// <summary>
  10. /// Bypasses a specified number of elements in an async-enumerable sequence and then returns the remaining elements.
  11. /// </summary>
  12. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  13. /// <param name="source">The sequence to take elements from.</param>
  14. /// <param name="count">The number of elements to skip before returning the remaining elements.</param>
  15. /// <returns>An async-enumerable sequence that contains the elements that occur after the specified index in the input sequence.</returns>
  16. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  17. /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is less than zero.</exception>
  18. public static IAsyncEnumerable<TSource> Skip<TSource>(this IAsyncEnumerable<TSource> source, int count)
  19. {
  20. if (source == null)
  21. throw Error.ArgumentNull(nameof(source));
  22. if (count <= 0)
  23. {
  24. // Return source if not actually skipping, but only if it's a type from here, to avoid
  25. // issues if collections are used as keys or otherwise must not be aliased.
  26. if (source is AsyncIteratorBase<TSource> || source is IAsyncPartition<TSource>)
  27. {
  28. return source;
  29. }
  30. count = 0;
  31. }
  32. else if (source is IAsyncPartition<TSource> partition)
  33. {
  34. return partition.Skip(count);
  35. }
  36. else if (source is IList<TSource> list)
  37. {
  38. return new AsyncListPartition<TSource>(list, count, int.MaxValue);
  39. }
  40. return new AsyncEnumerablePartition<TSource>(source, count, -1);
  41. }
  42. }
  43. }