ElementAt.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 Error.ArgumentNull(nameof(source));
  15. return ElementAtCore(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 Error.ArgumentNull(nameof(source));
  21. if (index < 0)
  22. throw Error.ArgumentOutOfRange(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. if (index < list.Count)
  30. {
  31. return list[index];
  32. }
  33. }
  34. else if (source is IAsyncPartition<TSource> p)
  35. {
  36. var first = await p.TryGetElementAsync(index, cancellationToken).ConfigureAwait(false);
  37. if (first.HasValue)
  38. {
  39. return first.Value;
  40. }
  41. else
  42. {
  43. throw Error.ArgumentOutOfRange(nameof(index));
  44. }
  45. }
  46. else
  47. {
  48. var e = source.GetAsyncEnumerator(cancellationToken);
  49. try
  50. {
  51. while (await e.MoveNextAsync().ConfigureAwait(false))
  52. {
  53. if (index == 0)
  54. {
  55. return e.Current;
  56. }
  57. index--;
  58. }
  59. }
  60. finally
  61. {
  62. await e.DisposeAsync().ConfigureAwait(false);
  63. }
  64. }
  65. throw Error.ArgumentOutOfRange(nameof(index));
  66. }
  67. }
  68. }