ElementAtOrDefault.cs 2.4 KB

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