ElementAt.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. public static Task<TSource> ElementAtAsync<TSource>(this IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken = default)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. return Core(source, index, cancellationToken);
  16. async Task<TSource> Core(IAsyncEnumerable<TSource> _source, int _index, CancellationToken _cancellationToken)
  17. {
  18. if (_source is IAsyncPartition<TSource> p)
  19. {
  20. var first = await p.TryGetElementAtAsync(_index, _cancellationToken).ConfigureAwait(false);
  21. if (first.HasValue)
  22. {
  23. return first.Value;
  24. }
  25. }
  26. else
  27. {
  28. if (_source is IList<TSource> list)
  29. {
  30. return list[_index];
  31. }
  32. if (_index >= 0)
  33. {
  34. #if CSHARP8 && AETOR_HAS_CT // CS0656 Missing compiler required member 'System.Collections.Generic.IAsyncEnumerable`1.GetAsyncEnumerator'
  35. await foreach (TSource item in _source.WithCancellation(_cancellationToken).ConfigureAwait(false))
  36. {
  37. if (_index == 0)
  38. {
  39. return item;
  40. }
  41. _index--;
  42. }
  43. #else
  44. var e = _source.GetAsyncEnumerator(_cancellationToken);
  45. try
  46. {
  47. while (await e.MoveNextAsync().ConfigureAwait(false))
  48. {
  49. if (_index == 0)
  50. {
  51. return e.Current;
  52. }
  53. _index--;
  54. }
  55. }
  56. finally
  57. {
  58. await e.DisposeAsync().ConfigureAwait(false);
  59. }
  60. #endif
  61. }
  62. }
  63. // NB: Even though index is captured, no closure is created.
  64. // The nameof expression is lowered to a literal prior to creating closures.
  65. throw Error.ArgumentOutOfRange(nameof(index));
  66. }
  67. }
  68. }
  69. }