如何在 C# 中从 TKey 获取字典 TValue?
我声明了字典 obj。
Dictionary<string, string> aDict = new Dictionary<string, string>();
aDict .Add("IP", "Host");
我记得,
aDict[IP]
的表达式可以返回值(Host)。
现在如果我朝相反的方向走。
如何从Value中获取Key? aDict[主机]
?
Dictionary 是 C# 中的一条单向街道,仅从 Key 到 Value 运行吗?谢谢。
I declared the dictionary obj.
Dictionary<string, string> aDict = new Dictionary<string, string>();
aDict .Add("IP", "Host");
As I remembered,
The expression of aDict[IP]
can return the value (Host).
Now if I go in the opposite direction.
How to get the Key from Value ? aDict[Host]
?
Does the Dictionary is a one-way street in C#, only running from Key to Value ? thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
字典不是这样工作的,也不是有意这样工作的。您将如何解决以下问题:
您可以这样做:
但是如果您确实需要在键和值之间来回切换,则应该考虑将问题封装到双向映射中。这是一个非常简单的实现,您可以根据需要进行定制:
请注意,这假设没有任何密钥重复。
现在你可以说:
Dictionaries do not work like this, nor are they intended to. How would you resolve the following:
You could do this:
But if you really need to go back and forth between keys and values you should consider encapsulating the problem into a two-way map. Here's a very simple implementation of this that you can tailor to your needs:
Note that this assumes that no key is ever duplicated.
Now you can say:
字典是一种单向查找。如果需要,您仍然可以循环遍历字典中的所有条目来查找值“Host”。如果您预计会经常这样做,您可能只想使用两个字典并使它们保持同步。
Dictionary is a one way lookup. You can still loop over all entries in the Dictionary looking for the value "Host" if you need to. If you anticipate doing that a lot you might just want to use two dictionaries to and keep them both in sync.
是的,字典基本上是一条单行道。例如,许多键可能具有值“Host”,因此没有简单的反向查找。
但是,您可以迭代字典,注意哪些键映射到所需的值:
显然,这对于大型字典来说效率不高。
Yes, the dictionary is basically a one way street. For example, it would be possible for many keys to have the value "Host", so there's no simple reverse lookup.
However, you can iterate over the dictionary noting which keys map to the desired value:
Obviously this is not efficient for large dictionaries though.
这是一条单向街道。值不应该是唯一的,因此您不能按值查找键,除非枚举整个字典:
It is a one way street. Values are not supposed to be unique, so you cannot look up a key by value, except by enumerating the whole dictionary: