ElementAtOrDefault.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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> ElementAtOrDefault<TSource>(this IAsyncEnumerable<TSource> source, int index)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. return ElementAtOrDefault(source, index, CancellationToken.None);
  16. }
  17. public static Task<TSource> ElementAtOrDefault<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 ElementAtOrDefaultCore(source, index, cancellationToken);
  24. }
  25. private static async Task<TSource> ElementAtOrDefaultCore<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.TryGetElementAt(index).ConfigureAwait(false);
  37. if (first.HasValue)
  38. {
  39. return first.Value;
  40. }
  41. }
  42. else
  43. {
  44. var e = source.GetAsyncEnumerator();
  45. try
  46. {
  47. while (await e.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  48. {
  49. if (index == 0)
  50. {
  51. return e.Current;
  52. }
  53. index--;
  54. }
  55. }
  56. finally
  57. {
  58. await e.DisposeAsync().ConfigureAwait(false);
  59. }
  60. }
  61. return default(TSource);
  62. }
  63. }
  64. }