diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs index 902e9168872cf4..2a65638c962f5c 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs @@ -375,24 +375,71 @@ public bool SetEquals(IEnumerable other) return true; } + if (other is ICollection otherAsICollectionGeneric) + { + if (otherAsICollectionGeneric.Count < this.Count) + { + return false; + } + + if (other is SortedSet otherAsSortedSet && otherAsSortedSet.Comparer == this.KeyComparer) + { + if (otherAsSortedSet.Count != this.Count) + { + return false; + } + var e1 = this.GetEnumerator(); + var e2 = otherAsSortedSet.GetEnumerator(); + while (e1.MoveNext() && e2.MoveNext()) + { + if (this.KeyComparer.Compare(e1.Current, e2.Current) != 0) + { + return false; + } + } + return true; + } + + else if (other is ImmutableSortedSet otherAsImmutableSortedSet && otherAsImmutableSortedSet.KeyComparer == this.KeyComparer) + { + if (otherAsImmutableSortedSet.Count != this.Count) + { + return false; + } + var e1 = this.GetEnumerator(); + var e2 = otherAsImmutableSortedSet.GetEnumerator(); + while (e1.MoveNext() && e2.MoveNext()) + { + if (this.KeyComparer.Compare(e1.Current, e2.Current) != 0) + { + return false; + } + } + return true; + } + } + + else if (other is ICollection otherAsICollection && otherAsICollection.Count < this.Count) + { + return false; + } + var otherSet = new SortedSet(other, this.KeyComparer); if (this.Count != otherSet.Count) { return false; } - - int matches = 0; - foreach (T item in otherSet) + var thisEnumerator = this.GetEnumerator(); + var otherSetEnumerator = otherSet.GetEnumerator(); + while (otherSetEnumerator.MoveNext() && thisEnumerator.MoveNext()) { - if (!this.Contains(item)) + if (this.KeyComparer.Compare(otherSetEnumerator.Current, thisEnumerator.Current) != 0) { return false; } - - matches++; } - return matches == this.Count; + return true; } ///