dictionary怎样通过key得到value

2025-03-25 08:53:11
推荐回答(2个)
回答1:

直接增加就行了 相同的KEY 后面的会覆盖前面的

key值有唯一性,value没有。

Dictionary是抽象类.

Dictionary ht =new Hashtable();
ht.get("");

//过时的类,现在用HashMap了.
望采纳,谢谢!!!

回答2:

Dictionary类,是一个abstract抽象类,定义得到value的方法为:V get(Object key)。
一般利用子类类Map的实现类HashMap等,调用get(key)方法得到value。
如下为一个十分简单的代码示例:
private void GetDicKeyByValue()
{
Dictionary dic = new Dictionary();
dic.Add("1", "1");
dic.Add("2", "2");
dic.Add("3", "2");
//foreach KeyValuePair traversing
foreach (KeyValuePair 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
}