好GetHash code()重写为富对象列表尊重秩序重写、秩序、对象、列表

2023-09-11 00:02:29 作者:绝世的画 缺了角就会掉

EnumerableObject:IEnumerable的<富>

包装了一个名单,其中,富>

如果 EnumerableObject a.SequenceEquals(EnumerableObject B),那么他们是平等的。

If EnumerableObject a.SequenceEquals( EnumerableObject b), then they are equal.

因此​​, GetHash code 必须执行。问题是异或列表中的每个元素将返回相同的哈希code表示与所有和仅有的相同的元件的任何列表中,不论顺序。这是奥凯在这方面的工作,反而会造成许多冲突,这会减慢检索等。

Therefore, a GetHashCode must be implemented. The problem is XORing each element in the list will return the same hash code for any list with all and only the same elements, regardless of order. This is Okay in terms of it working, but will result in many collisions, which will slow down retrieval, etc.

什么是好,速度快 GetHash code 方法对象列表是为了依赖?

What is a good, fast GetHashCode method for lists of objects that is order dependent?

推荐答案

我会做同样的方式,我通常结合哈希codeS - 用加法和乘法:

I'd do it the same way I normally combine hash codes - with an addition and a multiplication:

public override int GetHashCode()
{
    unchecked
    {
        int hash = 19;
        foreach (var foo in foos)
        {
            hash = hash * 31 + foo.GetHashCode();
        }
        return hash;
    }
}

(请注意,你不应该什么名单后,这已被用于任何种类哈希表的关键,作为散列将更改添加这还假定不存在空条目 - 如果有可能可以,你需要考虑到这一点。)

(Note that you shouldn't add anything to the list after this has been used for the key in a hash table of any description, as the hash will change. This also assumes that there are no null entries - if there could be, you need to take account of that.)