在C#中,有一个的IEqualityComparer< IEnumerable的>
使用的 SequenceEqual
法确定的平等
In C#, is there a IEqualityComparer<IEnumerable>
that uses the SequenceEqual
method to determine equality?
有没有这样的比较器在.NET Framework中,但你可以创建一个:
There is no such comparer in .NET Framework, but you can create one:
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)
{
if (obj == null)
return 0;
// Will not throw an OverflowException
unchecked
{
return obj.Select(e => e.GetHashCode()).Aggregate(17, (a, b) => 23 * a + b);
}
}
}
在上面的code,我遍历了 GetHash code
集合中的所有项目。我不知道这是否是最明智的解决方案,但是这就是在内部完成 HashSetEqualityComparer
。
In the above code, I iterate over all items of the collection in the GetHashCode
. I don't know if it's the wisest solution but this what is done in the internal HashSetEqualityComparer
.