从ConcurrentDictionary中按键获取KeyValuePair(在O(1)时间内) [英] Get KeyValuePair by Key from a ConcurrentDictionary (in O(1) time)

查看:141
本文介绍了从ConcurrentDictionary中按键获取KeyValuePair(在O(1)时间内)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此解决方案( https://stackoverflow.com/a/18923091/529618 ),我正在使用 ConcurrentDictionary< T,byte> 作为缺少 ConcurrentHashSet< T> 的解决方法。但是,我正在努力查看如何在O(1)时间内将原始 T键从字典中退回。

As per this solution (https://stackoverflow.com/a/18923091/529618) I am using a ConcurrentDictionary<T,byte> as a workaround for the lack of ConcurrentHashSet<T>. However, I'm struggling to see how I can get the original T Key back out of the dictionary in O(1) time.

var cache = new ConcurrentDictionary<MyEquatableClass, byte>());
//...
if(!cache.TryAdd(classInstance, Byte.MinValue))
    return /* Existing cache entry */;
return classInstance;

有什么方法可以获取 KeyValuePair< K,V> ConcurrentDictionary< K,V> 条目提供code>(甚至只是键),方法是给它一个等效的(IEquatable)键,而不用在O中进行枚举(n)时间?

Is there any way to get the KeyValuePair<K,V> (or even just the key) for a ConcurrentDictionary<K,V> entry by giving it an equivalent (IEquatable) key, without enumerating through it in O(n) time?

出现我的问题是因为我用作键的对象是 IEquatable< K> 彼此之间,但 ReferenceEqual 彼此之间没有。如果 myDict.ContainsKey(someEquatable),我想获取字典中的原始键实例(及其存储的值),并丢弃当前的(重复的)

My problem arises because the objects I'm using as Keys are IEquatable<K> to one another, but not ReferenceEqual to one-another. If myDict.ContainsKey(someEquatable), I want to get the original key instance in the dictionary (as well as the value stored with it), and throw away my current (duplicate) instance.

推荐答案

我刚刚意识到我可以从使用 ConcurrentDictionary< TKey,byte> ConcurrentDictionary< TKey,TKey> 。它的占用空间可能比字节值(未经证实)要大一些,但是如果值和键相同,则可以很容易地从该值中获取键。

I just realized I could just switch from using a ConcurrentDictionary<TKey, byte> to a ConcurrentDictionary<TKey, TKey>. It may have a bit of a heavier footprint than the byte value (unconfirmed), but if the value and key are the same, I can easily get the key from the value.

要将其扩展到发现此问题的人以及实际使用值的人,您可以选择将字典更改为 ConcurrentDictionary< TKey,Tuple< TKey,TValue> ,并同时获取原始键和值。

To extend this to those finding this question and who are actually using the "value", you can opt to change your dictionary to a ConcurrentDictionary<TKey, Tuple<TKey, TValue>, and get both the original key and the value that way.

var cache = new ConcurrentDictionary<MyEquatableClass, MyEquatableClass>());
//...
if(!cache.TryAdd(classInstance, classInstance))
    return cache[classInstance];
return classInstance;

这篇关于从ConcurrentDictionary中按键获取KeyValuePair(在O(1)时间内)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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