Dictionary类,是一个abstract抽象类,定义得到value的方法为62616964757a686964616fe59b9ee7ad9431333339663333:V get(Object key)。
一般利用子类类Map的实现类HashMap等,调用get(key)方法得到value。
如下为一个十分简单的代码示例:
private void GetDicKeyByValue()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add(“1”, “1”);
dic.Add(“2”, “2”);
dic.Add(“3”, “2”);
//foreach KeyValuePair traversing
foreach (KeyValuePair<string, string> kvp in dic)
{
if (kvp.Value.Equals(“2”))
{
//… kvp.Key;
}
}
//foreach dic.Keys
foreach (string key in dic.Keys)
{
if (dic[key].Equals(“2”))
{
//… key
}
}
//Linq
var keys = dic.Where(q => q.Value == “2”).Select(q => q.Key); //get all keys
List keyList = (from q in dic
where q.Value == “2”
select q.Key).ToList(); //get all keys
var firstKey = dic.FirstOrDefault(q => q.Value == “2”).Key; //get first key
}