Take.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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.take?view=net-9.0-pp#system-linq-asyncenumerable-take-1(system-collections-generic-iasyncenumerable((-0))-system-int32)
  11. /// <summary>
  12. /// Returns a specified number of contiguous elements from the start of an async-enumerable sequence.
  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 return.</param>
  17. /// <returns>An async-enumerable sequence that contains the specified number of elements from the start of 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> Take<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 Empty<TSource>();
  27. }
  28. else if (source is IAsyncPartition<TSource> partition)
  29. {
  30. return partition.Take(count);
  31. }
  32. else if (source is IList<TSource> list)
  33. {
  34. return new AsyncListPartition<TSource>(list, 0, count - 1);
  35. }
  36. return new AsyncEnumerablePartition<TSource>(source, 0, count - 1);
  37. }
  38. #endif // INCLUDE_SYSTEM_LINQ_ASYNCENUMERABLE_DUPLICATES
  39. }
  40. }