符合顺序的 Foo 对象列表的良好 GetHashCode() 覆盖 [英] Good GetHashCode() override for List of Foo objects respecting the order

查看:20
本文介绍了符合顺序的 Foo 对象列表的良好 GetHashCode() 覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EnumerableObject : IEnumerable

包装一个 List

如果EnumerableObject a.SequenceEquals(EnumerableObject b),则它们相等.

因此,必须实现 GetHashCode.问题是对列表中的每个元素进行 XOR 运算将返回相同的哈希码,对于任何包含所有且仅具有相同元素的列表,无论顺序如何.就其工作而言,这是可以的,但会导致许多冲突,这会减慢检索速度等.

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.

对于依赖顺序的对象列表,什么是好的、快速的 GetHashCode 方法?

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

推荐答案

我会按照我通常组合哈希码的方式来做 - 加上加法和乘法:

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

这篇关于符合顺序的 Foo 对象列表的良好 GetHashCode() 覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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