diff --git a/GameFrameX.Foundation.Extensions/IEnumerableExtensions.cs b/GameFrameX.Foundation.Extensions/IEnumerableExtensions.cs index 2ed74a1..761dc61 100644 --- a/GameFrameX.Foundation.Extensions/IEnumerableExtensions.cs +++ b/GameFrameX.Foundation.Extensions/IEnumerableExtensions.cs @@ -1223,28 +1223,74 @@ public static bool SequenceEqualSameType(this IEnumerable first, IEnumerab ArgumentNullException.ThrowIfNull(second, nameof(second)); ArgumentNullException.ThrowIfNull(condition, nameof(condition)); - if (first is ICollection source1 && second is ICollection source2) + if (TryCompareAsCollection(first, second, condition, out var collectionEqual)) { - if (source1.Count != source2.Count) - { - return false; - } + return collectionEqual; + } - if (source1 is IList list1 && source2 is IList list2) - { - var count = source1.Count; - for (var index = 0; index < count; ++index) - { - if (!condition(list1[index], list2[index])) - { - return false; - } - } + return CompareByEnumerator(first, second, condition); + } + /// + /// 尝试使用集合/列表优化路径比较两个相同类型的序列。 + /// + /// + /// Attempts to compare two same-typed sequences via the collection/list fast path. + /// Returns true when a collection-based decision was reached (caller must read + /// ); returns false when the caller must fall back to + /// the enumerator path. + /// + /// 序列中元素的类型 / The element type of the sequences + /// 第一个序列 / The first sequence + /// 第二个序列 / The second sequence + /// 用于比较两个元素的条件 / The condition to compare two elements + /// 当方法返回 true 时,输出基于集合路径的比较结果 / The comparison result when the method returns true + /// 如果集合路径能给出明确结论则返回 true,否则返回 false / true if the collection path yields a verdict; otherwise false + private static bool TryCompareAsCollection(IEnumerable first, IEnumerable second, Func condition, out bool isEqual) + { + isEqual = false; + + if (first is not ICollection source1 || second is not ICollection source2) + { + return false; + } + + if (source1.Count != source2.Count) + { + return true; + } + + if (source1 is not IList list1 || source2 is not IList list2) + { + return false; + } + + var count = source1.Count; + for (var index = 0; index < count; ++index) + { + if (!condition(list1[index], list2[index])) + { return true; } } + isEqual = true; + return true; + } + + /// + /// 使用枚举器逐个比较两个相同类型的序列。 + /// + /// + /// Compares two same-typed sequences element-by-element via . + /// + /// 序列中元素的类型 / The element type of the sequences + /// 第一个序列 / The first sequence + /// 第二个序列 / The second sequence + /// 用于比较两个元素的条件 / The condition to compare two elements + /// 如果两个序列长度相等且对应位置的元素都满足比较条件,则返回 true;否则返回 false / true if sequences have equal length and corresponding elements satisfy the comparison condition; otherwise false + private static bool CompareByEnumerator(IEnumerable first, IEnumerable second, Func condition) + { using var enumerator1 = first.GetEnumerator(); using var enumerator2 = second.GetEnumerator(); while (enumerator1.MoveNext())