好GetHash code()重写为富对象列表尊重秩序 [英] Good GetHashCode() override for List of Foo objects respecting the order

查看:180
本文介绍了好GetHash code()重写为富对象列表尊重秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.)

这篇关于好GetHash code()重写为富对象列表尊重秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆