ElementAt.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Cysharp.Threading.Tasks.Internal;
  2. using System;
  3. using System.Threading;
  4. namespace Cysharp.Threading.Tasks.Linq
  5. {
  6. public static partial class UniTaskAsyncEnumerable
  7. {
  8. public static UniTask<TSource> ElementAtAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken = default)
  9. {
  10. Error.ThrowArgumentNullException(source, nameof(source));
  11. return ElementAt.ElementAtAsync(source, index, cancellationToken, false);
  12. }
  13. public static UniTask<TSource> ElementAtOrDefaultAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken = default)
  14. {
  15. Error.ThrowArgumentNullException(source, nameof(source));
  16. return ElementAt.ElementAtAsync(source, index, cancellationToken, true);
  17. }
  18. }
  19. internal static class ElementAt
  20. {
  21. public static async UniTask<TSource> ElementAtAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, int index, CancellationToken cancellationToken, bool defaultIfEmpty)
  22. {
  23. var e = source.GetAsyncEnumerator(cancellationToken);
  24. try
  25. {
  26. int i = 0;
  27. while (await e.MoveNextAsync())
  28. {
  29. if (i++ == index)
  30. {
  31. return e.Current;
  32. }
  33. }
  34. if (defaultIfEmpty)
  35. {
  36. return default;
  37. }
  38. else
  39. {
  40. throw Error.ArgumentOutOfRange(nameof(index));
  41. }
  42. }
  43. finally
  44. {
  45. if (e != null)
  46. {
  47. await e.DisposeAsync();
  48. }
  49. }
  50. }
  51. }
  52. }