Contains.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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> ContainsAsync<TSource>(this IAsyncEnumerable<TSource> source, TSource value, CancellationToken cancellationToken = default) =>
  12. source is ICollection<TSource> collection ? Task.FromResult(collection.Contains(value)) :
  13. ContainsAsync(source, value, comparer: null, cancellationToken);
  14. public static Task<bool> ContainsAsync<TSource>(this IAsyncEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken = default)
  15. {
  16. if (source == null)
  17. throw Error.ArgumentNull(nameof(source));
  18. //
  19. // See https://github.com/dotnet/corefx/pull/25097 for the optimization here.
  20. //
  21. if (comparer == null)
  22. {
  23. return Core(source, value, cancellationToken);
  24. static async Task<bool> Core(IAsyncEnumerable<TSource> _source, TSource _value, CancellationToken _cancellationToken)
  25. {
  26. await foreach (TSource item in _source.WithCancellation(_cancellationToken).ConfigureAwait(false))
  27. {
  28. if (EqualityComparer<TSource>.Default.Equals(item, _value))
  29. {
  30. return true;
  31. }
  32. }
  33. return false;
  34. }
  35. }
  36. else
  37. {
  38. return Core(source, value, comparer, cancellationToken);
  39. static async Task<bool> Core(IAsyncEnumerable<TSource> _source, TSource _value, IEqualityComparer<TSource> _comparer, CancellationToken _cancellationToken)
  40. {
  41. await foreach (TSource item in _source.WithCancellation(_cancellationToken).ConfigureAwait(false))
  42. {
  43. if (_comparer.Equals(item, _value))
  44. {
  45. return true;
  46. }
  47. }
  48. return false;
  49. }
  50. }
  51. }
  52. }
  53. }