Contains.cs 2.7 KB

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