Except.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static IAsyncEnumerable<TSource> Except<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
  14. {
  15. if (first == null)
  16. throw new ArgumentNullException(nameof(first));
  17. if (second == null)
  18. throw new ArgumentNullException(nameof(second));
  19. return first.Except(second, EqualityComparer<TSource>.Default);
  20. }
  21. public static IAsyncEnumerable<TSource> Except<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
  22. {
  23. if (first == null)
  24. throw new ArgumentNullException(nameof(first));
  25. if (second == null)
  26. throw new ArgumentNullException(nameof(second));
  27. if (comparer == null)
  28. throw new ArgumentNullException(nameof(comparer));
  29. return CreateEnumerable(
  30. () =>
  31. {
  32. var e = first.GetEnumerator();
  33. var cts = new CancellationTokenDisposable();
  34. var d = Disposable.Create(cts, e);
  35. var mapTask = default(Task<Dictionary<TSource, TSource>>);
  36. var getMapTask = new Func<CancellationToken, Task<Dictionary<TSource, TSource>>>(
  37. ct => mapTask ?? (mapTask = second.ToDictionary(x => x, comparer, ct)));
  38. var f = default(Func<CancellationToken, Task<bool>>);
  39. f = async ct =>
  40. {
  41. if (await e.MoveNext(ct)
  42. .Zip(getMapTask(ct), (b, _) => b)
  43. .ConfigureAwait(false))
  44. {
  45. if (!mapTask.Result.ContainsKey(e.Current))
  46. return true;
  47. return await f(ct)
  48. .ConfigureAwait(false);
  49. }
  50. return false;
  51. };
  52. return CreateEnumerator(
  53. f,
  54. () => e.Current,
  55. d.Dispose,
  56. e
  57. );
  58. });
  59. }
  60. }
  61. }