简体   繁体   English

获取基于哈希的Dictionary或HashTable的值

[英]Get value of a Dictionary or HashTable based on a hash

I have a Dictionary where the keys are objects which are expensive to create. 我有一本Dictionary ,其中的键是创建昂贵的对象。 To avoid creating this objects every time I do a search, I have written a function to generate the hash of the object without actually creating it. 为了避免每次搜索都创建该对象,我编写了一个函数来生成对象的哈希,而无需实际创建它。 The problem is, I would like to use the generated hash to search in the Dictionary , but Dictionary doesn't expose such a method ( HashTable doesn't either). 问题是,我想使用生成的哈希值在Dictionary进行搜索,但是Dictionary不提供这种方法( HashTable也不提供)。

Is it possible to do what I want? 可以做我想做的吗?

Example

var dict = new Dictionary<ExpensiveObj, int>();
int i = dict.FindValueWithHash(generateHash()); // This is what I am looking for

Use an IEqualityComparer , supplied to the constructor, and use "cheap" algorithm internally to handle a "cheap pseudo-key" as applicable. 使用提供给构造函数的IEqualityComparer ,并在内部使用“ cheap”算法来处理“ cheap伪密钥”(如适用)。 1 1个

Look at the objects supplied - one will be a real object from the Dictionary, the other the "new"/pseudo-key object - to decide how to act. 查看提供的对象-一个是字典中的真实对象,另一个是“新” /伪键对象-确定如何操作。 The pseudo-key object will have to conform to the same type as the key to avoid a type error (go interfaces!), but can itself be "cheap to create". 伪密钥对象必须与密钥具有相同的类型,以避免类型错误(进入接口!),但它本身可以是“廉价的创建对象”。

Both the hash code generation and equality must be handled appropriately - otherwise a false-positive (ie. duplication hash) can result. 哈希码的生成相等性都必须得到适当的处理-否则会导致假阳性(即重复哈希)。

Or change the algorithm/data-structure so that such an approach is not required. 或更改算法/数据结构,以便不需要这种方法。


1 If a pseudo-key object always honors pseudo.Equals(real) == real.Equals(pseudo) and pseudo.GetHashCode() == real.GetHashCode() , such that the operations are "cheap" in all cases, then the custom comparer can be skipped as it would then merely bypass correct default behavior. 1如果伪密钥对象始终采用伪pseudo.Equals(real) == real.Equals(pseudo)pseudo.GetHashCode() == real.GetHashCode() ,那么在所有情况下操作都是“便宜”的,则可以跳过自定义比较器,因为它只会绕过正确的默认行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM