Intersect.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 IAsyncEnumerable<TSource> Intersect<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second) =>
  12. Intersect(first, second, comparer: null);
  13. public static IAsyncEnumerable<TSource> Intersect<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, IEqualityComparer<TSource>? comparer)
  14. {
  15. if (first == null)
  16. throw Error.ArgumentNull(nameof(first));
  17. if (second == null)
  18. throw Error.ArgumentNull(nameof(second));
  19. return Create(Core);
  20. async IAsyncEnumerator<TSource> Core(CancellationToken cancellationToken)
  21. {
  22. var set = new Set<TSource>(comparer);
  23. await foreach (var element in second.WithCancellation(cancellationToken).ConfigureAwait(false))
  24. {
  25. set.Add(element);
  26. }
  27. await foreach (var element in first.WithCancellation(cancellationToken).ConfigureAwait(false))
  28. {
  29. if (set.Remove(element))
  30. {
  31. yield return element;
  32. }
  33. }
  34. }
  35. }
  36. }
  37. }