ElementAtOrDefault.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. #if CSHARP8
  38. await foreach (TSource item in _source.WithCancellation(_cancellationToken).ConfigureAwait(false))
  39. {
  40. if (_index == 0)
  41. {
  42. return item;
  43. }
  44. _index--;
  45. }
  46. #else
  47. var e = _source.GetAsyncEnumerator(_cancellationToken);
  48. try
  49. {
  50. while (await e.MoveNextAsync().ConfigureAwait(false))
  51. {
  52. if (_index == 0)
  53. {
  54. return e.Current;
  55. }
  56. _index--;
  57. }
  58. }
  59. finally
  60. {
  61. await e.DisposeAsync().ConfigureAwait(false);
  62. }
  63. #endif
  64. }
  65. }
  66. return default;
  67. }
  68. }
  69. }
  70. }