1
0

ElementAt.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static Task<TSource> ElementAt<TSource>(this IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. if (index < 0)
  18. throw new ArgumentOutOfRangeException(nameof(index));
  19. return ElementAt_(source, index, cancellationToken);
  20. }
  21. public static Task<TSource> ElementAt<TSource>(this IAsyncEnumerable<TSource> source, int index)
  22. {
  23. if (source == null)
  24. throw new ArgumentNullException(nameof(source));
  25. return ElementAt(source, index, CancellationToken.None);
  26. }
  27. public static Task<TSource> ElementAtOrDefault<TSource>(this IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  28. {
  29. if (source == null)
  30. throw new ArgumentNullException(nameof(source));
  31. if (index < 0)
  32. throw new ArgumentOutOfRangeException(nameof(index));
  33. return ElementAtOrDefault_(source, index, cancellationToken);
  34. }
  35. public static Task<TSource> ElementAtOrDefault<TSource>(this IAsyncEnumerable<TSource> source, int index)
  36. {
  37. if (source == null)
  38. throw new ArgumentNullException(nameof(source));
  39. return ElementAtOrDefault(source, index, CancellationToken.None);
  40. }
  41. private static async Task<TSource> ElementAt_<TSource>(IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  42. {
  43. if (index >= 0)
  44. {
  45. using (var e = source.GetEnumerator())
  46. {
  47. while (await e.MoveNext(cancellationToken)
  48. .ConfigureAwait(false))
  49. {
  50. if (index == 0)
  51. {
  52. return e.Current;
  53. }
  54. index--;
  55. }
  56. }
  57. }
  58. throw new ArgumentOutOfRangeException(nameof(index));
  59. }
  60. private static async Task<TSource> ElementAtOrDefault_<TSource>(IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  61. {
  62. if (index >= 0)
  63. {
  64. using (var e = source.GetEnumerator())
  65. {
  66. while (await e.MoveNext(cancellationToken)
  67. .ConfigureAwait(false))
  68. {
  69. if (index == 0)
  70. {
  71. return e.Current;
  72. }
  73. index--;
  74. }
  75. }
  76. }
  77. return default(TSource);
  78. }
  79. }
  80. }