1
0

Intersect.cs 1.6 KB

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