SequenceEqual.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 ValueTask<bool> SequenceEqualAsync<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, CancellationToken cancellationToken = default) =>
  12. SequenceEqualAsync(first, second, comparer: null, cancellationToken);
  13. public static ValueTask<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. comparer ??= EqualityComparer<TSource>.Default;
  20. if (first is ICollection<TSource> firstCol && second is ICollection<TSource> secondCol)
  21. {
  22. if (firstCol.Count != secondCol.Count)
  23. {
  24. return new ValueTask<bool>(false);
  25. }
  26. if (firstCol is IList<TSource> firstList && secondCol is IList<TSource> secondList)
  27. {
  28. var count = firstCol.Count;
  29. for (var i = 0; i < count; i++)
  30. {
  31. if (!comparer.Equals(firstList[i], secondList[i]))
  32. {
  33. return new ValueTask<bool>(false);
  34. }
  35. }
  36. return new ValueTask<bool>(true);
  37. }
  38. }
  39. return Core(first, second, comparer, cancellationToken);
  40. static async ValueTask<bool> Core(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken)
  41. {
  42. await using (var e1 = first.GetConfiguredAsyncEnumerator(cancellationToken, false))
  43. {
  44. await using (var e2 = second.GetConfiguredAsyncEnumerator(cancellationToken, false))
  45. {
  46. while (await e1.MoveNextAsync())
  47. {
  48. if (!(await e2.MoveNextAsync() && comparer.Equals(e1.Current, e2.Current)))
  49. {
  50. return false;
  51. }
  52. }
  53. return !await e2.MoveNextAsync();
  54. }
  55. }
  56. }
  57. }
  58. }
  59. }