1
0

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