ElementAt.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. /// <summary>
  12. /// Returns the element at a specified index in a sequence.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  15. /// <param name="source">async-enumerable sequence to return the element from.</param>
  16. /// <param name="index">The zero-based index of the element to retrieve.</param>
  17. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  18. /// <returns>An async-enumerable sequence that produces the element at the specified position in the source sequence.</returns>
  19. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  20. /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than zero.</exception>
  21. /// <exception cref="ArgumentOutOfRangeException">(Asynchronous) <paramref name="index"/> is greater than or equal to the number of elements in the source sequence.</exception>
  22. public static ValueTask<TSource> ElementAtAsync<TSource>(this IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken = default)
  23. {
  24. if (source == null)
  25. throw Error.ArgumentNull(nameof(source));
  26. return Core(source, index, cancellationToken);
  27. static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  28. {
  29. if (source is IAsyncPartition<TSource> p)
  30. {
  31. var first = await p.TryGetElementAtAsync(index, cancellationToken).ConfigureAwait(false);
  32. if (first.HasValue)
  33. {
  34. return first.Value;
  35. }
  36. }
  37. else
  38. {
  39. if (source is IList<TSource> list)
  40. {
  41. return list[index];
  42. }
  43. if (index >= 0)
  44. {
  45. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  46. {
  47. if (index == 0)
  48. {
  49. return item;
  50. }
  51. index--;
  52. }
  53. }
  54. }
  55. // NB: Even though index is captured, no closure is created.
  56. // The nameof expression is lowered to a literal prior to creating closures.
  57. throw Error.ArgumentOutOfRange(nameof(index));
  58. }
  59. }
  60. }
  61. }