Zip.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. var e1 = first.GetEnumerator();
  23. var e2 = second.GetEnumerator();
  24. var current = default(TResult);
  25. var cts = new CancellationTokenDisposable();
  26. var d = Disposable.Create(cts, e1, e2);
  27. return CreateEnumerator(
  28. ct => e1.MoveNext(cts.Token)
  29. .Zip(e2.MoveNext(cts.Token), (f, s) =>
  30. {
  31. var result = f && s;
  32. if (result)
  33. current = selector(e1.Current, e2.Current);
  34. return result;
  35. }),
  36. () => current,
  37. d.Dispose
  38. );
  39. });
  40. }
  41. }
  42. }