IEqualityComparer for SequenceEqual

本文关键字:SequenceEqual for IEqualityComparer | 更新日期: 2023-09-27 17:57:10

在 C# 中,是否有使用 SequenceEqual 方法确定相等性的IEqualityComparer<IEnumerable>

IEqualityComparer for SequenceEqual

在.NET Framework中没有这样的比较器,但你可以创建一个:

public class IEnumerableComparer<T> : IEqualityComparer<IEnumerable<T>>
{
    public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
    {
        return Object.ReferenceEquals(x, y) || (x != null && y != null && x.SequenceEqual(y));
    }
    public int GetHashCode(IEnumerable<T> obj)
    {
        // Will not throw an OverflowException
        unchecked
        {
            return obj.Where(e => e != null).Select(e => e.GetHashCode()).Aggregate(17, (a, b) => 23 * a + b);
        }
    }
}

在上面的代码中,我遍历了GetHashCode集合的所有项。我不知道这是否是最明智的解决方案,但这是在内部HashSetEqualityComparer中完成的.

根据 Cédric Bignon 的答案创建了一个 NuGet 包:

组装包:https://www.nuget.org/packages/OBeautifulCode.Collection/

仅代码文件包:https://www.nuget.org/packages/OBeautifulCode.Collection.Recipes.EnumerableEqualityComparer/

var myEqualityComparer = new EnumerableEqualityComparer<string>();