ElementAtOrDefault.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 (index >= 0)
  28. {
  29. var e = source.GetAsyncEnumerator();
  30. try
  31. {
  32. while (await e.MoveNextAsync(cancellationToken).ConfigureAwait(false))
  33. {
  34. if (index == 0)
  35. {
  36. return e.Current;
  37. }
  38. index--;
  39. }
  40. }
  41. finally
  42. {
  43. await e.DisposeAsync().ConfigureAwait(false);
  44. }
  45. }
  46. return default(TSource);
  47. }
  48. }
  49. }