从字典中获取原始密钥对象 [英] get original key object from dictionary

查看:82
本文介绍了从字典中获取原始密钥对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个Dictionary< object,object和一个对象,确实

复制原始对象的Equals和GetHashCode用作

字典键,如何检索使用的原始密钥?

given a Dictionary<object, objectand an object that exactly
replicates the Equals and GetHashCode of the original object used as
the dictionary key, how do I retrieve the original key that was used?

推荐答案

我看不到一个简单的方法 - 也许你必须放下循环?

以一般(TKey / TValue)术语表示:


TKey testKey; //我们的等价但不同的密钥


IEqualityComparer< TKeycomparer = dict.Comparer;

foreach(KeyValuePair< TKey,TValuepair in dict){

if(comparer.Equals(testKey,pair.Key)){

return pair.Key; //原始(或克隆如果

blittable)

}

}

抛出新的KeyNotFoundException() ;


Marc
I can''t see an easy way - perhaps you have to drop down to looping?
Shown in the general (TKey / TValue) terms:

TKey testKey; // our equivalent but different key

IEqualityComparer<TKeycomparer = dict.Comparer;
foreach (KeyValuePair<TKey, TValuepair in dict) {
if (comparer.Equals(testKey, pair.Key)) {
return pair.Key; // the original (or a clone if
blittable)
}
}
throw new KeyNotFoundException();

Marc


我不确定这里的目标是什么。如果你使用ContainsKey方法

并且它返回true,你知道你拥有它,对吗?

- Peter

网站: http://www.eggheadcafe.com

UnBlog: http://petesbloggerama.blogspot.com

MetaFinder: http://www.blogmetafinder.com

" not_a_commie"写道:
Not sure I understand the objective here. If you used the ContainsKey method
and it returns true, you know you have it, correct?
-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
MetaFinder: http://www.blogmetafinder.com
"not_a_commie" wrote:

给定一个字典< object,object和一个对象,确切地说

复制用作
字典键,如何检索使用的原始密钥?
given a Dictionary<object, objectand an object that exactly
replicates the Equals and GetHashCode of the original object used as
the dictionary key, how do I retrieve the original key that was used?


不确定我是否理解这里的目标。如果你使用ContainsKey方法
Not sure I understand the objective here. If you used the ContainsKey method

并且它返回true,你知道你拥有它,对吗?
and it returns true, you know you have it, correct?



我相信OP意味着他有两个不同的对象(大概是

类)他认为是相同的 - 即它们代表相同的

客户,但是是不同的实例。他打算使用他手中的b $ b。找到在

字典中用作关键字的原文。在处理外墙,飞锤等时非常常见。


我以前见过这个,但我想我已经结束了

年我更喜欢使用灵长类钥匙......


Marc

I believe the OP means that he has two different objects (presumably
classes) that he considers equal - i.e. they represent the same
Customer, but are different instances. He intends to use the one he
has "in hand" to find the original that was used as the key in the
dictionary. Quite common when dealing with facades, flyweights, etc.

I have seen this done before, but I think I''ve concluded over the
years that I prefer to use primatives for keys...

Marc


这篇关于从字典中获取原始密钥对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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