Dictionary对象可以通过VALUE读取KEY吗
展开全部
Dictionary类,是一个abstract抽象类,定义得到value的方法为: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<string> keyList = (from q in dic
where q.Value == "2"
select q.Key).ToList<string>(); //get all keys
var firstKey = dic.FirstOrDefault(q => q.Value == "2").Key; //get first 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<string> keyList = (from q in dic
where q.Value == "2"
select q.Key).ToList<string>(); //get all keys
var firstKey = dic.FirstOrDefault(q => q.Value == "2").Key; //get first key
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询