的IEqualityComparer为SequenceEqual [英] IEqualityComparer for SequenceEqual
问题描述
在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
集合中的所有项目。我不知道这是否是最明智的解决方案,但是这就是在内部完成<一个href="http://referencesource.microsoft.com/#System.Core/System/Collections/Generic/HashSetEqualityComparer.cs"相对=nofollow> 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
.
这篇关于的IEqualityComparer为SequenceEqual的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!