Contains.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 Task<bool> Contains<TSource>(this IAsyncEnumerable<TSource> source, TSource value)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. return ContainsCore(source, value, EqualityComparer<TSource>.Default, CancellationToken.None);
  16. }
  17. public static Task<bool> Contains<TSource>(this IAsyncEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
  18. {
  19. if (source == null)
  20. throw new ArgumentNullException(nameof(source));
  21. if (comparer == null)
  22. throw new ArgumentNullException(nameof(comparer));
  23. return ContainsCore(source, value, comparer, CancellationToken.None);
  24. }
  25. public static Task<bool> Contains<TSource>(this IAsyncEnumerable<TSource> source, TSource value, CancellationToken cancellationToken)
  26. {
  27. if (source == null)
  28. throw new ArgumentNullException(nameof(source));
  29. return ContainsCore(source, value, EqualityComparer<TSource>.Default, cancellationToken);
  30. }
  31. public static Task<bool> Contains<TSource>(this IAsyncEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken)
  32. {
  33. if (source == null)
  34. throw new ArgumentNullException(nameof(source));
  35. if (comparer == null)
  36. throw new ArgumentNullException(nameof(comparer));
  37. return ContainsCore(source, value, comparer, cancellationToken);
  38. }
  39. private static Task<bool> ContainsCore<TSource>(IAsyncEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken)
  40. {
  41. return source.Any(x => comparer.Equals(x, value), cancellationToken);
  42. }
  43. }
  44. }