Take.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. /// Returns a specified number of contiguous elements from the start of an async-enumerable sequence.
  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 return.</param>
  15. /// <returns>An async-enumerable sequence that contains the specified number of elements from the start of 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> Take<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 Empty<TSource>();
  25. }
  26. else if (source is IAsyncPartition<TSource> partition)
  27. {
  28. return partition.Take(count);
  29. }
  30. else if (source is IList<TSource> list)
  31. {
  32. return new AsyncListPartition<TSource>(list, 0, count - 1);
  33. }
  34. return new AsyncEnumerablePartition<TSource>(source, 0, count - 1);
  35. }
  36. }
  37. }