ElementAtOrDefault.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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. /// <summary>
  12. /// Returns the element at a specified index in a sequence or a default value if the index is out of range.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  15. /// <param name="source">async-enumerable sequence to return the element from.</param>
  16. /// <param name="index">The zero-based index of the element to retrieve.</param>
  17. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  18. /// <returns>An async-enumerable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.</returns>
  19. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  20. /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than zero.</exception>
  21. public static ValueTask<TSource?> ElementAtOrDefaultAsync<TSource>(this IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken = default)
  22. {
  23. if (source == null)
  24. throw Error.ArgumentNull(nameof(source));
  25. return Core(source, index, cancellationToken);
  26. static async ValueTask<TSource?> Core(IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken)
  27. {
  28. if (source is IAsyncPartition<TSource> p)
  29. {
  30. var first = await p.TryGetElementAtAsync(index, cancellationToken).ConfigureAwait(false);
  31. if (first.HasValue)
  32. {
  33. return first.Value;
  34. }
  35. }
  36. if (index >= 0)
  37. {
  38. if (source is IList<TSource> list)
  39. {
  40. if (index < list.Count)
  41. {
  42. return list[index];
  43. }
  44. }
  45. else
  46. {
  47. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  48. {
  49. if (index == 0)
  50. {
  51. return item;
  52. }
  53. index--;
  54. }
  55. }
  56. }
  57. return default;
  58. }
  59. }
  60. }
  61. }