Zip.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. public static IAsyncEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IAsyncEnumerable<TFirst> first, IAsyncEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector)
  13. {
  14. if (first == null)
  15. throw new ArgumentNullException(nameof(first));
  16. if (second == null)
  17. throw new ArgumentNullException(nameof(second));
  18. if (selector == null)
  19. throw new ArgumentNullException(nameof(selector));
  20. return CreateEnumerable(
  21. () =>
  22. {
  23. var e1 = first.GetEnumerator();
  24. var e2 = second.GetEnumerator();
  25. var current = default(TResult);
  26. var cts = new CancellationTokenDisposable();
  27. var d = Disposable.Create(cts, e1, e2);
  28. return CreateEnumerator(
  29. ct => e1.MoveNext(cts.Token)
  30. .Zip(e2.MoveNext(cts.Token),
  31. (f, s) =>
  32. {
  33. var result = f && s;
  34. if (result)
  35. current = selector(e1.Current, e2.Current);
  36. return result;
  37. }),
  38. () => current,
  39. d.Dispose
  40. );
  41. });
  42. }
  43. }
  44. }