我如何检查是否HashSet的包含使用项目的散列值的项目吗? [英] How can I check if a HashSet contains an item using the hash of the item?

查看:85
本文介绍了我如何检查是否HashSet的包含使用项目的散列值的项目吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查,如果HashSet的包含特定元素。我已经有元素的 INT 散列码而不是元素本身的引用。

I want to check if a HashSet contains a specific element. I already have the int hashcode of the element but not a reference to the element itself.

是否有可能做到这一点没有遍历整套?

Is it possible to do this without iterating over the whole set?

推荐答案

没有,因为


  • 存在的哈希码没有人一对一映射对象(鸽子原则

  • HashSet的 / 词典别ŧ让本implementaion详情

  • there is no one-to-one mapping of hash code to object (pigeon principle)
  • .Net HashSet / Dictionary don't expose this implementaion details

如果你真的需要找到哈希代码,你可以

If you really need to find object by hash code you can


  • 遍历所有项目,并比较哈希代码

  • 如果这是主要的功能 - 考虑,如果自定义比较,可以让你有特殊的对象,将匹配用相同的散列码的任何其他对象将工作...

  • 特殊的比较器
  • iterate all items and compare hash code
  • if this is main functionality - consider if custom comparer that will let you have special object that will match any other object with the same hash code will work...

近似代码

 class ObjectsToStore
 {
     ....
     public int? HashCodeOverwrite; 
 }

 class ComparerByHashCode : IEqualityComparer<ObjectsToStore>
 {

   public bool Equals(ObjectsToStore b1, ObjectsToStore b2)
   {
       if (b1.HashCodeOverwrite.HasValue || b2.HashCodeOverwrite.HasValue)
       {
           return b1.GetHashCode() == b2.GetHashCode());
       }
       // add all null checks here too.
       return b1.Equals(b2);
   }

   public int GetHashCode(ObjectsToStore b)
   {
     return b.HashCodeOverwrite.HasValue? b.HashCodeOverwrite.Value:b.GetHashCode();
   }
 }



近似用法:

Approximate usage:

var myHashSet = new HashSet<ObjectsToStore>(new ComparerByHashCode());
var itemByHashCode = myHashSet[new ObjectsToStore{HasCodeOverwrite= 1234}];

这篇关于我如何检查是否HashSet的包含使用项目的散列值的项目吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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