ElementAtOrDefault.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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> ElementAtOrDefaultAsync<TSource>(this IAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken = default)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. return Core(source, index, cancellationToken);
  16. async Task<TSource> Core(IAsyncEnumerable<TSource> _source, int _index, CancellationToken _cancellationToken)
  17. {
  18. if (_source is IAsyncPartition<TSource> p)
  19. {
  20. var first = await p.TryGetElementAtAsync(_index, _cancellationToken).ConfigureAwait(false);
  21. if (first.HasValue)
  22. {
  23. return first.Value;
  24. }
  25. }
  26. if (_index >= 0)
  27. {
  28. if (_source is IList<TSource> list)
  29. {
  30. if (_index < list.Count)
  31. {
  32. return list[_index];
  33. }
  34. }
  35. else
  36. {
  37. var e = _source.GetAsyncEnumerator(_cancellationToken);
  38. try
  39. {
  40. while (await e.MoveNextAsync().ConfigureAwait(false))
  41. {
  42. if (_index == 0)
  43. {
  44. return e.Current;
  45. }
  46. _index--;
  47. }
  48. }
  49. finally
  50. {
  51. await e.DisposeAsync().ConfigureAwait(false);
  52. }
  53. }
  54. }
  55. return default;
  56. }
  57. }
  58. }
  59. }