ElementAt.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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> ElementAt<TSource>(this IAsyncEnumerable<TSource> source, int index)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. return ElementAt(source, index, CancellationToken.None);
  16. }
  17. public static Task<TSource> ElementAt<TSource>(this IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  18. {
  19. if (source == null)
  20. throw new ArgumentNullException(nameof(source));
  21. if (index < 0)
  22. throw new ArgumentOutOfRangeException(nameof(index));
  23. return ElementAtCore(source, index, cancellationToken);
  24. }
  25. private static async Task<TSource> ElementAtCore<TSource>(IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  26. {
  27. if (source is IList<TSource> list)
  28. {
  29. return list[index];
  30. }
  31. if (index >= 0)
  32. {
  33. var e = source.GetAsyncEnumerator();
  34. try
  35. {
  36. while (await e.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  37. {
  38. if (index == 0)
  39. {
  40. return e.Current;
  41. }
  42. index--;
  43. }
  44. }
  45. finally
  46. {
  47. await e.DisposeAsync().ConfigureAwait(false);
  48. }
  49. }
  50. throw new ArgumentOutOfRangeException(nameof(index));
  51. }
  52. }
  53. }