ElementAtOrDefault.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. static 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. await foreach (TSource item in _source.WithCancellation(_cancellationToken).ConfigureAwait(false))
  38. {
  39. if (_index == 0)
  40. {
  41. return item;
  42. }
  43. _index--;
  44. }
  45. }
  46. }
  47. return default;
  48. }
  49. }
  50. }
  51. }