Contains.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. if (source is ICollection<TSource> collection)
  16. {
  17. return Task.FromResult(collection.Contains(value));
  18. }
  19. return ContainsCore(source, value, comparer: null, cancellationToken);
  20. }
  21. public static Task<bool> ContainsAsync<TSource>(this IAsyncEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken = default)
  22. {
  23. if (source == null)
  24. throw Error.ArgumentNull(nameof(source));
  25. return ContainsCore(source, value, comparer, cancellationToken);
  26. }
  27. private static async Task<bool> ContainsCore<TSource>(IAsyncEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken)
  28. {
  29. var e = source.GetAsyncEnumerator(cancellationToken);
  30. try
  31. {
  32. //
  33. // See https://github.com/dotnet/corefx/pull/25097 for the optimization here.
  34. //
  35. if (comparer == null)
  36. {
  37. while (await e.MoveNextAsync().ConfigureAwait(false))
  38. {
  39. if (EqualityComparer<TSource>.Default.Equals(e.Current, value))
  40. {
  41. return true;
  42. }
  43. }
  44. }
  45. else
  46. {
  47. while (await e.MoveNextAsync().ConfigureAwait(false))
  48. {
  49. if (comparer.Equals(e.Current, value))
  50. {
  51. return true;
  52. }
  53. }
  54. }
  55. }
  56. finally
  57. {
  58. await e.DisposeAsync().ConfigureAwait(false);
  59. }
  60. return false;
  61. }
  62. }
  63. }