从 .Net 集合中的值获取键
我正在使用 StringDictionary 来存储键值对。 我需要互换使用键和值,即我应该能够从值中获取键,因为在我的情况下,值将是不同的。
有没有直接的方法可以做到这一点(无需循环)? 或者如果我可以使用任何其他集合来实现此目的?
目前我正在循环:
public String GetKeyFromValue(string value)
{
foreach (KeyValuePair<string, string> kvp in instance)
{
if (String.Equals(kvp.Value, value))
return kvp.Key;
}
throw new Exception ("Key not found in FilterControlMapping");
}
非常感谢任何帮助。 谢谢。
I am using a StringDictionary to store key value pairs. I need to use the keys and values interchangeably i.e. I should be able to get the key from the value as in my case the values will be distinct.
Is there a direct way I could do it (without looping)? Or if there is any other collection I could use to achieve this?
Currently I am looping:
public String GetKeyFromValue(string value)
{
foreach (KeyValuePair<string, string> kvp in instance)
{
if (String.Equals(kvp.Value, value))
return kvp.Key;
}
throw new Exception ("Key not found in FilterControlMapping");
}
Any help is much appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您基本上需要使用封装成一个的两个字典。
这里已经有了实现和此处在其他 Stack Overflow 问题中。
You basically need to use two dictionaries encapsulated into one.
There are already implementations here and here in other Stack Overflow questions.
我能想到的唯一方法是两本字典。
D1< 键、值>
D2< 值、键>
不过,您会重复您的数据。 但您可以通过这种方式搜索键和值。
The only way I can think of is two dictionaries.
D1 < Key, Value >
D2 < Value, Key >
You would be repeating your data though. But you could search both keys and values this way.
最好的想法是使用 Dictionary 而不是 StringDictionary 作为其过时的..
您可以在这里找到更多相关信息:
StringDictionary 与 Dictionary
关于检索,您应该在内部使用 linq,它使用循环,但仍然是更干净的方式。
The best idea is to use Dictionary instead of StringDictionary as its obselete..
you can find out more about this here:
StringDictionary vs Dictionary<string, string>
regarding retrival you should go with linq internally it is using loops but still its much cleaner way..
使用 Dictionary 也可以做到这一点:
请注意,如果该值出现多次,则 Single 方法将抛出异常。 您可以使用 First 甚至 FirstOrDefault。
编辑:
正如乔恩·斯基特(Jon Skeet)评论的那样,这仍然在循环。 他发布到链接词典的链接提供了解决方案。
This would also be possible using Dictionary:
Note that the Single method will throw if the value occurs more than once. You could use First or even FirstOrDefault.
Edit:
As Jon Skeet commented this is still looping. The links he posted to a linked dictionary provide the solution.