ElementAt.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. return ElementAtCore(source, index, CancellationToken.None);
  16. }
  17. public static Task<TSource> ElementAtAsync<TSource>(this IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  18. {
  19. if (source == null)
  20. throw Error.ArgumentNull(nameof(source));
  21. return ElementAtCore(source, index, cancellationToken);
  22. }
  23. private static async Task<TSource> ElementAtCore<TSource>(IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  24. {
  25. if (source is IAsyncPartition<TSource> p)
  26. {
  27. var first = await p.TryGetElementAtAsync(index, cancellationToken).ConfigureAwait(false);
  28. if (first.HasValue)
  29. {
  30. return first.Value;
  31. }
  32. }
  33. else
  34. {
  35. if (source is IList<TSource> list)
  36. {
  37. return list[index];
  38. }
  39. if (index >= 0)
  40. {
  41. var e = source.GetAsyncEnumerator(cancellationToken);
  42. try
  43. {
  44. while (await e.MoveNextAsync().ConfigureAwait(false))
  45. {
  46. if (index == 0)
  47. {
  48. return e.Current;
  49. }
  50. index--;
  51. }
  52. }
  53. finally
  54. {
  55. await e.DisposeAsync().ConfigureAwait(false);
  56. }
  57. }
  58. }
  59. throw Error.ArgumentOutOfRange(nameof(index));
  60. }
  61. }
  62. }