SequenceEqual.cs 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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> SequenceEqualAsync<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, CancellationToken cancellationToken = default) =>
  12. SequenceEqualAsync(first, second, comparer: null, cancellationToken);
  13. public static Task<bool> SequenceEqualAsync<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken = default)
  14. {
  15. if (first == null)
  16. throw Error.ArgumentNull(nameof(first));
  17. if (second == null)
  18. throw Error.ArgumentNull(nameof(second));
  19. if (comparer == null)
  20. {
  21. comparer = EqualityComparer<TSource>.Default;
  22. }
  23. if (first is ICollection<TSource> firstCol && second is ICollection<TSource> secondCol)
  24. {
  25. if (firstCol.Count != secondCol.Count)
  26. {
  27. return Task.FromResult(false);
  28. }
  29. if (firstCol is IList<TSource> firstList && secondCol is IList<TSource> secondList)
  30. {
  31. int count = firstCol.Count;
  32. for (int i = 0; i < count; i++)
  33. {
  34. if (!comparer.Equals(firstList[i], secondList[i]))
  35. {
  36. return Task.FromResult(false);
  37. }
  38. }
  39. return Task.FromResult(true);
  40. }
  41. }
  42. return Core(first, second, comparer, cancellationToken);
  43. static async Task<bool> Core(IAsyncEnumerable<TSource> _first, IAsyncEnumerable<TSource> _second, IEqualityComparer<TSource> _comparer, CancellationToken _cancellationToken)
  44. {
  45. var e1 = _first.GetConfiguredAsyncEnumerator(_cancellationToken, false);
  46. try // REVIEW: Can use `await using` if we get pattern bind (HAS_AWAIT_USING_PATTERN_BIND)
  47. {
  48. var e2 = _second.GetConfiguredAsyncEnumerator(_cancellationToken, false);
  49. try // REVIEW: Can use `await using` if we get pattern bind (HAS_AWAIT_USING_PATTERN_BIND)
  50. {
  51. while (await e1.MoveNextAsync())
  52. {
  53. if (!(await e2.MoveNextAsync() && _comparer.Equals(e1.Current, e2.Current)))
  54. {
  55. return false;
  56. }
  57. }
  58. return !await e2.MoveNextAsync();
  59. }
  60. finally
  61. {
  62. await e2.DisposeAsync();
  63. }
  64. }
  65. finally
  66. {
  67. await e1.DisposeAsync();
  68. }
  69. }
  70. }
  71. }
  72. }