ElementAt.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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();
  16. async Task<TSource> Core()
  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. var e = source.GetAsyncEnumerator(cancellationToken);
  35. try
  36. {
  37. while (await e.MoveNextAsync().ConfigureAwait(false))
  38. {
  39. if (index == 0)
  40. {
  41. return e.Current;
  42. }
  43. index--;
  44. }
  45. }
  46. finally
  47. {
  48. await e.DisposeAsync().ConfigureAwait(false);
  49. }
  50. }
  51. }
  52. throw Error.ArgumentOutOfRange(nameof(index));
  53. }
  54. }
  55. }
  56. }