通过使用字典值获取字典键 [英] Get Dictionary key by using the dictionary value
本文介绍了通过使用字典值获取字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用字典值的字典键
How to get the dictionary key by using the dictionary value?
让使用该密钥的这样的值时:
when getting the value using the key its like this:
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "a");
Console.WriteLine(dic[1]);
Console.ReadLine();
如何做相反的?
推荐答案
一个字典是真的打算从密钥 - >值的一种方式查找。
A dictionary is really intended for one way lookup from Key->Value.
您可以做相反的使用LINQ:
You can do the opposite use LINQ:
var keysWithMatchingValues = dic.Where(p => p.Value == "a").Select(p => p.Key);
foreach(var key in keysWithMatchingValues)
Console.WriteLine(key);
认识到,有可能是多个键具有相同的值,因此,任何适当的搜索将返回的集合键(这就是为什么上面的foreach存在)。
Realize that there may be multiple keys with the same value, so any proper search will return a collection of keys (which is why the foreach exists above).
这篇关于通过使用字典值获取字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文