Skip.cs 2.4 KB

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